开发者

Target on click

开发者 https://www.devze.com 2023-02-04 09:14 出处:网络
Look this code: <div> <a href = \"#\"><span>Click me MAN !</span></a> </div>

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

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


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.

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.

Live example: 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);


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

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


Can't you just use

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号