javascript/jquery 用数组中的随机文本有条件地替换文本

javascript/jquery to replace text conditionally with random text from an array

如果某个字符串符合特定条件,我想用数组中的随机字符串替换该字符串。

到目前为止我有这个(没有解决条件部分)。

html:

<div>
   <span class ="test">foo</span>
</div>
<div>
   <span class ="test">bar</span>
</div>
<div>
   <span class ="test">test</span>
</div>
<div>
   <span class ="test">random</span>
</div>

代码:

$(".test").each(function () {
var quotes = new Array("foo", "bar", "baz", "chuck"),
    randno = quotes[Math.floor(Math.random() * quotes.length)];

    $('.test').text(randno);
});

这会设置每个“.test”class 相同的东西。我得到:

foo


foo


酒吧
酒吧
酒吧


  1. 如果字符串等于"foo",我如何让它只替换字符串?

  2. 如果我有多个 "foos" 我如何让每个 "foo" 随机替换而不是全部设置为相同的东西?

需要在.each()回调方法中使用this

$(".test").each(function() {
    var quotes = new Array("foo", "bar", "baz", "chuck"),
        randno = quotes[Math.floor(Math.random() * quotes.length)];

    //Check condition
    if ($(this).text() === "foo") {
        $(this).text(randno);
    }
});

或者您也可以使用 .text(function)

var quotes = new Array("foo", "bar", "baz", "chuck");
$(".test").text(function(_, text) {
    var randno = quotes[Math.floor(Math.random() * quotes.length)];

    //Check condition
    if (text === "foo") {
        return randno;
    }
    return text;
});

$(function() {
  var quotes = new Array("foo", "bar", "baz", "chuck");
  $(".test").text(function(_, text) {
    var randno = quotes[Math.floor(Math.random() * quotes.length)];

    //Check condition
    if (text === "foo") {
      return randno;
    }
    return text;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span class="test">foo</span>
</div>
<div>
  <span class="test">bar</span>
</div>
<div>
  <span class="test">test</span>
</div>
<div>
  <span class="test">random</span>
</div>

另一种方法是打乱替换数组,而不是使用它:

/* Famous shuffle function */
Array.prototype.shuffle = function() {
    for (var j, x, i = this.length; i; j = Math.floor(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
    return this;
};

$.fn.extend({
    randomReplace: function(text, replacements) {
        replacements.shuffle();
        return this.each(function () {
            if( $(this).text().toLowerCase()==text.toLowerCase() )
                $(this).text(replacements.pop());
        });
    }
});

$('.test').randomReplace('foo', ['one', 'two', 'three', 'four', 'five', 'six']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="test">foo</span>
<span class="test">bar</span>
<span class="test">foo</span>
<span class="test">foo</span>
<span class="test">bar</span>