0

我想<p>在窗口或文档级别侦听元素上的事件,因为此类元素太多,无法为每个元素附加 onclick 事件处理程序。

这就是我所拥有的:

window.onload=function()
{
    window.addEventListener('click',onClick,false);
}
function onClick(event)
{
    alert(event.target.nodeName.toString());
}

我需要关于上面代码的建议,它好吗?而且,如何检查单击的元素是否是<p>除检查之外的元素nodeName?例如,如果<p>元素包含一个<b>元素并且被单击,则 nodeType 将b不是p

谢谢你。

4

3 回答 3

1

考虑一下:

(function () {

    // returns true if the given node or any of its ancestor nodes
    // is of the given type
    function isAncestor( node, type ) {
        while ( node ) {
            if ( node.nodeName.toLowerCase() === type ) {
               return true;
            } 
            node = node.parentNode;
        }
        return false;
    }

    // page initialization; runs on page load
    function init() {

        // global click handler
        window.addEventListener( 'click', function (e) {
            if ( isAncestor( e.target, 'p' ) ) {
                 // a P element was clicked; do your thing   
            }
        }, false );

    }

    window.onload = init;

})();

现场演示:http: //jsfiddle.net/xWybT/

于 2011-09-10T22:58:56.807 回答
1

我认为这很好,您可以通过这种方式进行检查

var e = event.target
while (e.tagName != 'P')
   if (!(e = e.parentNode))
       return
alert(e)
于 2011-09-10T22:39:34.823 回答
1

如果我是你,我会以与“点击”相同的方式注册“加载”事件。这是一种更现代的事件处理方式,但某些旧浏览器可能不支持。

检查 nodeName 是询问节点的最佳方法:

function onClick(event) {
    var el = event.target;
    while (el && "P" != el.nodeName) {
        el = el.parentNode;
    }
    if (el) {
        console.log("found a P!");
    }
}
于 2011-09-10T22:42:19.737 回答