单击 jQuery 查找最近的元素
Find closest element on click with jQuery
我通过单击嵌套元素来触发函数。为了防止冒泡,我可以使用 e.stopPropagation();
.
如果停止传播,其他脚本就会遇到麻烦,因为它们依赖于冒泡这些元素。还有另一种解决方法吗?某种 if 语句?
html
<div class="nested-element">
<div class="nested-element">
content
</div>
content
</div>
现实生活中嵌套是无限的
jquery
$('.selector').on('click', '.nested-element', function(e) {
//e.stopPropagation();
console.log($(this));
});
上面会先输出根parent,然后再靠近最近的元素。我只想获取最近的元素。
您可以检查 target
如果目标在 class 的后代实例中则什么也不做
$(document).on('click', '.nested-element', function(e) {
if(!$(e.target).closest('.nested-element').not(this).length){
console.log('nested-element clicked =', this.id);
}else{
console.log('Ignore parent event')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent" class="nested-element">
<div id="child" class="nested-element">
child content
</div>
parent content
</div>
我通过单击嵌套元素来触发函数。为了防止冒泡,我可以使用 e.stopPropagation();
.
如果停止传播,其他脚本就会遇到麻烦,因为它们依赖于冒泡这些元素。还有另一种解决方法吗?某种 if 语句?
html
<div class="nested-element">
<div class="nested-element">
content
</div>
content
</div>
现实生活中嵌套是无限的
jquery
$('.selector').on('click', '.nested-element', function(e) {
//e.stopPropagation();
console.log($(this));
});
上面会先输出根parent,然后再靠近最近的元素。我只想获取最近的元素。
您可以检查 target
如果目标在 class 的后代实例中则什么也不做
$(document).on('click', '.nested-element', function(e) {
if(!$(e.target).closest('.nested-element').not(this).length){
console.log('nested-element clicked =', this.id);
}else{
console.log('Ignore parent event')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent" class="nested-element">
<div id="child" class="nested-element">
child content
</div>
parent content
</div>