如何将相同的jQuery代码应用于同一个类的两个实例?

时间:2011-09-06 15:08:28

标签: javascript jquery class

例如我有这段代码:

$('.note .exit').click(function() {
  $('.note').fadeOut();
});

在我的HTML上有两个.exit和.note实例。如:

<div class="note">
        <img src="images/exit.png" class="exit"/>

        <p>Some text.</p>   
</div>

<div class="note">
        <img src="images/exit.png" class="exit"/>

        <p>Some other text.</p> 
</div>

问题是当我单击一个.note的关闭按钮(退出图像)时,另一个.note也会关闭。如何修改代码,使其仅适用于我正在关闭的特定.note类?

3 个答案:

答案 0 :(得分:6)

使用.closest() [docs]获取与选择器匹配的最近祖先:

$('.note .exit').click(function() {
  $(this).closest('.note').fadeOut();
});

根据您的结构,您还可以使用.parent() [docs]

答案 1 :(得分:2)

使用$(this).parent().fadeOut() ... this将是点击发生的.exit

答案 2 :(得分:1)

试试这个:

 $('.note .exit').click(function() {
  $(this).closest('.note').fadeOut();
});
相关问题