Attach event handlers for click event on all elements in the DOM

后端 未结 3 1056
春和景丽
春和景丽 2021-01-20 02:41

So I want to be able to figure out which part of my page has been clicked. There is no guarantee the elements are all on the page from the get go, which means that I need to

相关标签:
3条回答
  • 2021-01-20 03:03

    currentTarget returns the node to which the event has bubbled (if at all). Instead, interrogate target, so:

    Vanilla:

    document.addEventListener('click', function(evt) {
        alert(evt.target.tagName);
    }, false);
    

    jQuery:

    $(document).on('click', function(evt) {
        alert(evt.target.tagName);
    });
    

    http://jsfiddle.net/qsbdr/

    0 讨论(0)
  • 2021-01-20 03:10

    Try this:

    $(document).on('click', function(e) {
       // now use e.target here
    });
    

    You can also kill the bubbling on the click event by using e.stopPropagation()

    0 讨论(0)
  • 2021-01-20 03:20

    I don't see any need to use jQuery for something like this, though my suggestion does rely on MutationEvents, which I understand are to be replaced.

    You can get notified upon the insertion of any new node into the DOM. In the callback that fires, you can trivially attach an onclick handler to the new node. I've only handled the case where new nodes are added.

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    window.addEventListener('load', onDocLoaded, false);
    
    function onDocLoaded()
    {
        window.addEventListener('DOMNodeInserted', onNodeInserted, false);
        document.body.appendChild( newEl('div') );
    }
    
    function onNodeInserted(evt)
    {
        evt.srcElement.addEventListener('click', onNodeClicked, false);
    }
    
    function onNodeClicked()
    {
        document.body.appendChild( newEl('div') );
    }
    </script>
    <style>
    div
    {
        border: solid 1px red;
        padding: 8px;
        margin: 4px;
        display: inline-block;
    }
    </style>
    </head>
    <body>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题