在窗口级别监听某些元素上的事件 - Javascript,无库
我想在窗口或文档级别侦听
元素上的事件,因为此类元素太多,无法为每个元素附加 onclick 事件处理程序。
这就是我所得到的:
window.onload=function()
{
window.addEventListener('click',onClick,false);
}
function onClick(event)
{
alert(event.target.nodeName.toString());
}
我需要关于上面代码的建议,它好吗? 另外,除了检查 nodeName
之外,如何检查单击的元素是否是
元素? 例如,如果
元素包含 元素并且被单击,则 nodeType 将为
b
而不是 <代码>p。
谢谢。
I want to listen for events on <p>
elements at window or document level as there are too many such elements to attach an onclick event hander for each.
This is what I've got:
window.onload=function()
{
window.addEventListener('click',onClick,false);
}
function onClick(event)
{
alert(event.target.nodeName.toString());
}
I need advice on the code above, is it good?
And also, how can I check if the clicked element is a <p>
element other than checking nodeName
?
For example, if the <p>
element contains a <b>
element and that is clicked, the nodeType will be b
not p
.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑一下:
现场演示: http://jsfiddle.net/xWybT/
Consider this:
Live demo: http://jsfiddle.net/xWybT/
我觉得很好,你可以这样检查
I think it is good, and you can perform checking this way
如果我是你,我会像注册“点击”事件一样注册“加载”事件。这是一种更现代的事件处理方式,但某些较旧的浏览器可能不支持。
检查节点名称是询问节点的最佳方法:
If I was you I'd register for the "load" event in the same way that you are for "click". It's a more modern way of event handling, but might not be supported by some older browsers.
Checking the nodeName is the best way to interrogate the node: