javascript 为 DOM 中的所有元素上的 click 事件附加事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22700664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:36:35  来源:igfitidea点击:

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

javascriptjqueryeventsdomjavascript-events

提问by praks5432

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 use something like jquery delegate.

所以我希望能够弄清楚我的页面的哪一部分被点击了。不能保证元素从一开始就都在页面上,这意味着我需要使用诸如 jquery 委托之类的东西。

One way to do this is to iterate through all elements in the DOM and then attach an event handler to each element - but this will be slow and complicated - everytime new html is dynamically added, I'd have to either re-attach all the handlers, or figure out the subset of html that was added.

一种方法是遍历 DOM 中的所有元素,然后将事件处理程序附加到每个元素 - 但这会很慢而且很复杂 - 每次动态添加新的 html 时,我都必须重新附加所有处理程序,或找出添加的 html 子集。

The other way is to use event bubbling - so add an event handler to the document, or body and rely upon the events bubbling up

另一种方法是使用事件冒泡 - 所以向文档或正文添加一个事件处理程序并依赖于冒泡的事件

something like this

像这样的东西

        $('body').delegate('div', 'click', function(e){
            dummyId++;
            console.log(e);
            console.log(e.currentTarget);
            console.log("=====");

        });

However, after using this code, when I click on buttons on my page, I get the div surrounding the button, as opposed to the actual button. In other words, the above is too specific. Furthermore, I feel like the original selector should be the document, rather than the body tag.

但是,在使用此代码后,当我单击页面上的按钮时,我会看到按钮周围的 div,而不是实际按钮。换句话说,上面的内容太具体了。此外,我觉得原始选择器应该是文档,而不是正文标签。

To be clear, I want to know when any element is clicked on my page - how do I do that?

明确地说,我想知道何时点击了我页面上的任何元素 - 我该怎么做?

Thanks

谢谢

SO I tried this code with .on

所以我用 .on 尝试了这段代码

$(document).on('click', function(e){
    console.log("EVENT DUMMY ID");

    console.log(e.target);
    console.log("=====");

});

However, when I click on buttons in my app, nothing gets triggered - when I click on other elements, the console logs run.

但是,当我单击应用程序中的按钮时,不会触发任何内容 - 当我单击其他元素时,控制台日志会运行。

I understand this is probably hard to answer without more context - what else do you need?

我知道如果没有更多背景,这可能很难回答 - 您还需要什么?

回答by Utkanos

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

currentTarget返回事件冒泡到的节点(如果有的话)。相反, interrogate target,所以:

Vanilla:

香草:

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

jQuery:

jQuery:

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

http://jsfiddle.net/qsbdr/

http://jsfiddle.net/qsbdr/

回答by dima

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()

您还可以通过使用来消除点击事件上的冒泡 e.stopPropagation()

回答by enhzflep

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.

我认为没有必要将 jQuery 用于这样的事情,尽管我的建议确实依赖于 MutationEvents,据我所知,它将被替换。

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.

您可以在将任何新节点插入 DOM 时收到通知。在触发的回调中,您可以轻松地将 onclick 处理程序附加到新节点。我只处理了添加新节点的情况。

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