开发者

capturing event on parent element

开发者 https://www.devze.com 2023-01-03 03:09 出处:网络
window.event reports the lowest element in the tree when a click happens. e.g. <a href=\"http://server.com/page.aspx\" id=\"anchor\">

window.event reports the lowest element in the tree when a click happens. e.g.

<a href="http://server.com/page.aspx" id="anchor">
<span id="span" class="Someclass">
    <strong id="strong">Submit</strong> 
</span> </a>

When you click on the above link and if you have onclick listner at BODY level, the window.event will report that "st开发者_开发问答rong" element got clicked. In the same event, how do I know that the parent is actually an "anchor" tag which has href pointing somewhere? i.e. I am looking for an automatic way for me to know the main element is "anchor" and not "strong" element. I clearly can't do window.event.target.parentNode.parentNode as this will be manual checking. May be somewhere I can follow the "bubbling" of the click event.

Anyone any clue?


You can check the ancestors automatically.

var element = foo;
while (foo !== document.body) {
    if (foo === someCondition) {
      return foo;
    }
    foo = foo.parentNode;
}
return false;

Most libraries have a method to do this built in. e.g. YUI 3 has Node.ancestor, and jQuery has closest.

0

精彩评论

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