简体   繁体   English

单击带有 JQuery 输出的 List-Items 到许多结果

[英]Clicking List-Items with JQuery outputs to many results

I do have a list item which looks like this:我确实有一个看起来像这样的列表项:

在此处输入图片说明

HTML HTML

<ul>
    <li id="nav-menu-item-7" class="menu-element">
        <a href="google.com">TEST 2</a>
        <ul>
            <li id="nav-menu-item-8" class="menu-element">TEST 3</a></li>
            <li id="nav-menu-item-11" class="menu-element">
                PAGE 4
                <ul>
                    <li id="nav-menu-item-77" class="menu-element"><a href="http://google.com" class="menu-link sub-menu-link">LINK</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

JQUERY查询

$(document).ready(function(){
    $(document).on('click', '.menu-element', function(e){
        var id = $(this).attr('id').replace(/\D/g,'');

        alert(id);
    });
});

I simply want to output the numeric ID of the container in an popup which i achieve with JQuery.我只想在我用 JQuery 实现的弹出窗口中输出容器的数字 ID。 The Problem that i am having now it that i get an Popup for the element i clicked and for the parent objects.我现在遇到的问题是我为我单击的元素和父对象获得了一个弹出窗口。 This means in this case 77,11,7.在这种情况下,这意味着 77,11,7。 I only want the first element to be ouput, means the 77 without having to change the whole structure of the menu.我只希望输出第一个元素,即 77,而不必更改菜单的整个结构。 Any Ideas?有任何想法吗? Thank you.谢谢你。

Just stop the event propagation to the parent elements:只需停止事件传播到父元素:

  $(document).on('click', '.menu-element', function(e){

        e.stopPropagation();

        var id = $(this).attr('id').replace(/\D/g,'');
        alert(id);
    });

You should read about how events traverse the DOM, first from the document root to the clicked elements, then down to the document object.您应该了解事件如何遍历 DOM,首先从文档根到单击的元素,然后再到文档对象。 You can stop the propagation in both phases.您可以在两个阶段停止传播。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM