admin管理员组文章数量:1313006
I have following html:
<div id="div1">
<div id="div2">
</div>
</div>
JS:
document.addEventListener('mousedown', function(e){
console.log(e.target);
});
If mouse is clicked on div2, then e.target
is div2. I want target to be div1 in this case. Is it possible?
I have following html:
<div id="div1">
<div id="div2">
</div>
</div>
JS:
document.addEventListener('mousedown', function(e){
console.log(e.target);
});
If mouse is clicked on div2, then e.target
is div2. I want target to be div1 in this case. Is it possible?
- Yes it is. It's also much easier with a supporting library like jQuery. – Alex Wayne Commented Jan 1, 2013 at 0:00
- 7 I don't want to use jQuery – karaxuna Commented Jan 1, 2013 at 0:01
-
1
What is your ultimate goal? Do you need to trigger an event for
div1
or modifydiv1
in some way? – Michael Berkowski Commented Jan 1, 2013 at 0:02 - try using e.target.parentElement to get div1 – AgnosticDev Commented Jan 1, 2013 at 0:03
- I'm getting attribute of e.target, depending on that attribute I decide I can do some action or not (div1 has that attribute) – karaxuna Commented Jan 1, 2013 at 0:04
2 Answers
Reset to default 5The simplest way is probably to walk upward up the DOM tree until you find the element you want.
document.addEventListener('mousedown', function(e) {
// start with the element that was clicked.
var parent = e.target;
// loop while a parent exists, and it's not yet what we are looking for.
while (parent && parent.id !== 'div1') {
// We didn't find anything yet, so snag the next parent.
parent = parent.parentElement;
}
// When the loop exits, we either found the element we want,
// or we ran out of parents.
console.log(parent);
});
Example: http://jsfiddle/7kYJn/
In DOM, you can specify which element to attach the event listener to:
var div1 = document.getElementById('div1');
div1.addEventListener('mousedown',function(e){
console.log(e.target);
});
本文标签: javascriptChanging event targetStack Overflow
版权声明:本文标题:javascript - Changing event target - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741869347a2402101.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论