我有一堆嵌套列表:
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3
<ul>
<li>child-1</li>
<li>child-2
<ul>
<li>grand-child 1</li>
</ul>
</li>
</ul>
</li>
</ul>
通过 jQuery,通过单击或悬停,我想使用该元素 (li)。但它给了我它的 parent 。 如:如果我单击(或悬停)孙子 1,$(this) 返回 ITEM-3( parent 的 parent )
我的 jQuery 代码:
$('ul li').live('click', function(e) {
someVar = $(this).data("dataname"); // (can be .attr(""), etc.);
});
当单击任何一个 Li 时,我如何使用该特定的 Li,而不使用它嵌套的父级?
最佳答案
这会有帮助吗?如果您看到console.log,它只返回当前单击的元素。阅读有关 stopPropagation 的文档 here 。
"The docs states that stopPropagation Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event."
我还将 live 更新为 on,因为 live 从 1.7 开始已被弃用
$('ul li').on('click', function(e) {
e.stopPropagation();
console.log($(this));
});
关于javascript - 选择单击的元素而不是其父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9519836/