【问题标题】:Jquery - Variables being indexed across the whole dom instead of in each instanceJquery - 在整个 dom 中而不是在每个实例中索引变量
【发布时间】:2016-03-10 21:32:02
【问题描述】:

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

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

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>

【问题讨论】:

    标签: jquery this each


    【解决方案1】:

    这是因为您在每个循环中选择了 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();
      })();
    });
    

    【讨论】:

    • 你是明星,我必须弄清楚发生了什么事情会更好,但我使用的是第一个解决方案!
    猜你喜欢
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2013-08-23
    • 2017-10-06
    • 2018-10-13
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    相关资源
    最近更新 更多