选择单击的图元,而不是其父图元

Selecting the clicked element and not its parents

本文关键字:图元 单击 选择      更新时间:2023-09-26

我有一堆嵌套列表:

<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)。但它给了我它的父母。如:如果我点击(或悬停)grand-child 1,$(this)返回ITEM-3(父级的父级)

我的jQuery代码:

$('ul li').live('click', function(e) {
    someVar = $(this).data("dataname"); // (can be .attr(""), etc.);
});

当点击任何一个Li时,我怎么能使用那个特定的,而不是它嵌套的父项?

这有帮助吗。如果您看到console.log,它只返回当前单击的项目。请在此处阅读stopPropagation的文档。

"文档声明stopPropagation阻止事件在DOM树中冒泡,阻止任何父处理程序不会收到事件通知。"

我还将live更新为on,因为live从1.7 开始就被弃用了

$('ul li').on('click', function(e) {
   e.stopPropagation();
   console.log($(this)); 
}); 

我想下面就是你想要的,

$('ul li').live('click', function(e) {
    e.stopPropagation();
    someVar = $(this).data("dataname"); 
});

e.stopPropagation();停止传播到其他匹配ul li 的任何事件

注意:如果使用jQuery v1.7,请使用.on,因为.live已弃用。

$(document).on('click', 'ul li', function(e) {
    e.stopPropagation();
    alert($(this).text()); // (can be .attr(""), etc.);
});

DEMO