javascript 点击目标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4642866/
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-25 14:24:02  来源:igfitidea点击:

Target on click

javascripteventstarget

提问by Caio

Look this code:

看这个代码:

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

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".

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

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

谢谢,不,我不想使用“parentNode”。

回答by Tim Down

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 直到命中一个<a>元素,要么将侦听器附加到链接本身并使用this.

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.

尽量减少事件侦听器的数量通常是一个好主意,因此这里有一个如何遍历 DOM 的示例。注意事件监听器在不支持addEventListener()DOM节点的方法的IE中不起作用。

Live example: http://jsfiddle.net/timdown/pJp4J/

现场示例: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);

回答by piayo

Add the this css tips for JavaScript. You will get event.target you want.

为 JavaScript 添加 this css 提示。你会得到你想要的 event.target 。

a > *,
button > *{
  pointer-events:none;
}

回答by Cray

Can't you just use

你不能只用

<span><a href="#">Click me</a></span> ?