我创建了一个语音气泡,显示我存储在列表中的引号。当我点击气泡时,它随机从列表中选择另一个引号,但有时会选择它已经显示的那个。我怎么能阻止它这样做?
<ul class="joke-list">
<li id="quotes">
<span style="color: rgb(0, 0, 0);"><span style="font-size: medium;">Charles Darwin wanted to be a doctor but did not like the sight of blood.</span></span></li>
<li id="quotes">
<span style="color: rgb(0, 0, 0);"><span style="font-size: medium;">Charles Darwin was a member of the Gourmet Club. He ate lots of animals including armadillos, owls and tigers.</span></span></li>
<li id="quotes">
<span style="color: rgb(0, 0, 0);"><span style="font-size: medium;">For his 25th Birthday, Charles Darwin had a mountain named after him in Zimbabwe. </span></span></li>
</ul>
答案 0 :(得分:2)
这应该解决它
$.fn.extend({
rnditem : function(l) {
var current = $(this).text(),
next = (l.eq(Math.floor(Math.random() * l.length)).text());
while (next === current) {
next = (l.eq(Math.floor(Math.random() * l.length)).text());
}
$(this).text(next);
return this;
}
});
$(document).ready(function () {
var list = $(".joke-list").find("#quotes");
$(document.body).on('click','.speech', function () {
$(this).rnditem(list);
});
$(".speech").trigger("click");
});
上
在回答下面的其他问题时,解决方案将是
$.fn.extend({
rnditem : function(l) {
var a = [],
current = $(this).text().trim(),
index,
next;
Array.prototype.forEach.call(l, function(item) {
a.push($(item).text().trim());
});
index = a.indexOf(current) + 1;
if (index < 0 || index >= l.length) {
index = 0;
}
next = (l.eq(index).text());
$(this).text(next);
return this;
}
});
上