如果该字符串等于某个条件,我想用数组中的随机字符串替换该字符串。
到目前为止我已经有了这个(它没有解决条件部分)。
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”类设置为相同的东西。我得到:
富
富
富
foo
或
栏
酒吧
酒吧
栏
如何使其仅替换等于“foo”的字符串?
如果我有多个“foo”,我如何获得它替换的每个“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>
关于javascript/jquery 有条件地用数组中的随机文本替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31058285/