2

我创建了一个气泡,显示我存储在列表中的引号。当我单击气泡时,它会随机从列表中选择另一个引用,但有时会选择它已经显示的引用。我将如何防止它这样做?

<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>

小提琴:http: //jsfiddle.net/FsjkM/236/

4

1 回答 1

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");

});

jsfiddle 上

在回答您下面的其他问题时,解决方案是

$.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;
   }
 });

jsfiddle 上

于 2013-04-18T11:09:35.753 回答