【问题标题】:How to add a closure to jQuery .each function?如何向 jQuery .each 函数添加闭包?
【发布时间】:2015-06-10 09:10:37
【问题描述】:

我有两个这样的类的链接:

<a href="#" class="button post-12">Babylon</a>
<a href="#" class="button post-47">Sumer</a>
<a href="#" class="button post-87">Ur</a>

我不希望这些按钮中的每一个都隐藏相关帖子,例如,单击具有“post-12”类的链接将隐藏此:

<p id="post-12">Babylon was an aicient city...</p>

为了实现这一点,我有这个 jQuery 脚本。但始终是 ID 为“post-87”的帖子以所有三个按钮关闭。

var secondClass;
$('.button').each(function(){
    secondClass = $(this).attr('class');
    secondClass = secondClass.replace('button ','');
    $(this).click(function(){
        $('#'+secondClass+'').hide();
    });
});

我在这里做错了什么?如何给 jQuery .each 函数添加闭包?

【问题讨论】:

    标签: jquery variables each


    【解决方案1】:

    更改您的 secondClass 声明的范围:

    $('.button').each(function(){
        var secondClass = $(this).attr('class');
        secondClass = secondClass.replace('button ','');
        $(this).click(function(){
            $('#'+secondClass+'').hide();
        });
    });
    

    【讨论】:

      【解决方案2】:

      我认为我们可以在您的场景中利用 -data:

      <a href="#" data-divid="post-12" class="button post-12">Babylon</a>
      <a href="#" data-divid="post-47" class="button post-47">Sumer</a>
      <a href="#" data-divid="post-87" class="button post-87">Ur</a>
      
      $('.button').click(function(){
          var divtoclose = $(this).data("divid");
          $('#'+divtoclose).hide();
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-12
        • 1970-01-01
        • 1970-01-01
        • 2012-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多