Jquery - 变量在整个 dom 中索引,而不是在每个实例中索引

Jquery - Variables being indexed across the whole dom instead of in each instance

所以我有一个页面我正在尝试添加一个快速循环遍历项目列表的翻转部分 - 但是当我在页面上有两个独立列表时,列表项目被索引为一个大列表而不是两个较小的列表。

本质上,变量索引列表中的所有项目,而不是每个列表上的 运行

jQuery

  <script type="text/javascript">

      jQuery('.flipper').each(function() {

(function flipperexec() {
    var quotes =  jQuery('.flipper').children(".content");
    var quoteIndex = -1;
function showNextQuote() {
        ++quoteIndex;
        quotes.eq(quoteIndex % quotes.length).fadeIn(50).delay(100).fadeOut(50, showNextQuote);
}
showNextQuote();
})();

      });
  </script>

示例 HTML 列表 1 和 2

<ul class="flipper"><li class="content" style="display: none;">classes</li><li class="content" style="display: none;">coffee</li><li class="content" style="display: inline-block;">taste</li></ul>


<ul class="flipper"><li class="content" style="display: none;">classes</li><li class="content" style="display: none;">coffee</li><li class="content" style="display: inline-block;">taste</li></ul>

这是因为您在每个循环中选择了 IIFE 内的所有 $('.flipper') 元素:

$('.flipper').children(".content");

您需要引用您正在迭代的当前 .flipper 元素。您可以在 IIFE 之外设置 this 的值:

$('.flipper').each(function() {
  var self = this;
  (function flipperexec() {
    var quotes = $(self).children(".content");

    // ...
  }());
});

或者您可以从 .each() 循环中传递的参数中获取对元素的引用:

Example Here

$('.flipper').each(function(i, el) {
  (function flipperexec() {
    var quotes = $(el).children(".content");
    var quoteIndex = -1;

    function showNextQuote() {
      ++quoteIndex;
      quotes.eq(quoteIndex % quotes.length).fadeIn(50).delay(100).fadeOut(50, showNextQuote);
    }
    showNextQuote();
  })();
});