在DOM中的所有元素上为click事件附加事件处理程序 [英] Attach event handlers for click event on all elements in the DOM

查看:80
本文介绍了在DOM中的所有元素上为click事件附加事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我希望能够确定页面的哪一部分已被单击.不能一开始就保证所有元素都在页面上,这意味着我需要使用jquery委托之类的东西.

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.

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

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.

另一种方法是使用事件冒泡-因此,将事件处理程序添加到文档或正文中,并依赖于事件冒泡

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

类似的东西

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

        });

但是,使用此代码后,当我单击页面上的按钮时,得到的是围绕按钮的div,而不是实际的按钮.换句话说,以上内容过于具体.此外,我觉得原始选择器应该是文档,而不是body标签.

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.

要清楚,我想知道何时单击页面上的任何元素-我该怎么做?

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

谢谢

所以我在.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?

推荐答案

currentTarget返回事件冒泡的节点(如果有的话).相反,请询问target,所以:

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

香草:

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

jQuery:

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

http://jsfiddle.net/qsbdr/

这篇关于在DOM中的所有元素上为click事件附加事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆