javascript - 选择单击的元素而不是其父元素

标签 javascript jquery css

我有一堆嵌套列表:

<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/

相关文章:

javascript - 我的 "Includes"如何破坏独立 Google Apps 脚本中的表单提交?

javascript - 在顶部显示受 CSS3 动画影响的 div

javascript - 如何在 jquery 中获取按钮的上下文?

javascript - 获取日期和货币格式

html - 如何在 IE7 中用 "display:inline-block"覆盖 "display: block"?

jquery - 下拉菜单 CSS 或 jQuery

javascript - 如何使用sqlite在插入查询中获取插入的行id?

javascript - CasperJS填充adwords关键词规划器

jquery - 使用 jQuery 打印 JSON 对象

html - 在悬停时缩放和模糊图像