例如我有以下代码:
$('.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类?
最佳答案
使用.closest()
获取与选择器匹配的最接近的祖先:
$('.note .exit').click(function() {
$(this).closest('.note').fadeOut();
});
根据您的结构,您也可以使用
.parent()
。