如何获取作为(e)传递的元素的ID?
window.addEventListener('load', function(){
var tags = document.getElementsByClassName("tag");
for (i=0; i<tags.length; i++){
tags[i].addEventListener('mousedown', function(e){ tagClick(e) }, false);
}
}, false);
function tagClick(e){
/* here I'm gonna need the event to cancel the bubble and the ID to work with it*/
alert('The id of the element you clicked: ' + [?object].id);
[?object].className='newClass';
e.stopPropagation();
e.cancelBubble = true;
}
Run Code Online (Sandbox Code Playgroud)
我需要在tagClick中获取元素/对象,以便我可以更改其属性
HTML:
<div class="tag">
<img src="/images/tags/sample.jpg"/>
<label class="tagLabel">Sample</label>
</div>
Run Code Online (Sandbox Code Playgroud)
请注意,附加事件的元素是div,但是当使用e.srcElement时,ig会给我图像对象.
T.J*_*der 12
绑定事件侦听器时addEventListener,会通过this引用绑定事件的元素来调用它.所以,this.id将成为id元素的(如果有的话).
alert('The id of the element you clicked: ' + this.id);
Run Code Online (Sandbox Code Playgroud)
但你用这一行打破了这个:
tags[i].addEventListener('mousedown', function(e){ tagClick(e) }, false);
Run Code Online (Sandbox Code Playgroud)
...因为你在中间放了一个额外的功能,然后tagClick没有设置就打电话this.不需要额外的功能,将其更改为:
tags[i].addEventListener('mousedown', tagClick, false);
Run Code Online (Sandbox Code Playgroud)
......所以this不要搞砸了.或者,如果您希望使用额外功能,请确保this使用Function#call以下方法进行维护:
tags[i].addEventListener('mousedown', function(e){ tagClick.call(this, e) }, false);
Run Code Online (Sandbox Code Playgroud)
...但是没有理由使用所tagClick显示的功能.
(标准)事件对象也具有属性target(可能不是您绑定事件的元素,它可能是后代)和currentTarget(它将是您绑定事件的元素).但this如果您使用addEventListener(甚至attachEvent在IE上),则方便可靠.
您可以使用 获取事件的目标e.target。
但是请记住,某些浏览器将文本节点视为目标,因此请尝试以下操作:
var t = e.target;
while(t && !t.id) t = t.parentNode;
if( t) {
alert("You clicked element #"+t.id);
}
Run Code Online (Sandbox Code Playgroud)
这将找到实际具有 ID 的第一个元素。
新年快乐!
编辑:再想一想,如果它是您要引用的“标签”元素本身,只需使用this. 在事件处理程序中,this指的是实际具有处理程序的元素。尽管在这种情况下,您需要将处理程序更改为('mousedown', tagClick, false)
或者更好:
document.body.addEventListener("mousedown",function(e) {
var t = e.target;
while(t && t.nodeName != "TAG") { // note, must be uppercase
t = t.parentNode;
}
if( t) {
alert("You clicked on #"+t.id);
}
},false);
Run Code Online (Sandbox Code Playgroud)
事件处理程序越少越好。