目标点击 [英] Target on click

查看:127
本文介绍了目标点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看以下代码:

<div>
    <a href = "#"><span>Click me MAN !</span></a>
</div>

<script type = "text/javascript">
    window.onload = function () {
        document.body.addEventListener ("click", function (event) {
            var target = event.target;

            alert ("Returns \"" + target.nodeName + "\". Just want \"" + target.parentNode.nodeName + "\"")
        }, false);
    }
</script>

当您点击链接时,您可以在链接中看到元素span当前目标是相同的跨度。如何event.target返回link而不是span。

You can see the element "span" inside a "link", when the "link" is clicked the current target is the same "span". How can the "event.target" return "link" instead of "span".

谢谢而不,我不想使用parentNode p>

Thanks and no, I don't want to use "parentNode".

推荐答案

使用您的方法,您必须手动遍历DOM,直到您点击< a> 元素或将侦听器附加到链接本身,并使用

With your approach, you either have to manually traverse up the DOM until you hit an <a> element or attach the listener to the link itself and use this.

最小化事件侦听器的数量通常是一个好主意,所以这里是一个如何遍历DOM的例子。请注意,事件监听器不能在IE中运行,不支持DOM节点的 addEventListener()方法。

Minimizing the number of event listeners is generally a good idea, so here's an example of how to traverse the DOM. Note that the event listener will not work in IE, which does not support the addEventListener() method of DOM nodes.

现场示例: http://jsfiddle.net/timdown/pJp4J/

function getAncestor(node, tagName) {
    tagName = tagName.toUpperCase();
    while (node) {
        if (node.nodeType == 1 && node.nodeName == tagName) {
            return node;
        }
        node = node.parentNode;
    }
    return null;
}

document.body.addEventListener("click", function(event) {
    var target = getAncestor(event.target, "a");
    if (target !== null) {
        alert(target.nodeName);
    }
}, false);

这篇关于目标点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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