Javascript 如何在 getElementsByClassName 中获取当前元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11075819/
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
How to get current element in getElementsByClassName
提问by Googlebot
Consider a simple JS event of
考虑一个简单的 JS 事件
document.getElementsByClassName('test')[0].onclick=function(){
document.getElementsByClassName('test')[0].innerHTML = 'New Text';
}
How can I extend this code to generally work for all elements with class="test"
. I mean getting the element clicked and replace its content. In fact, we need to get the node number (provided inside the bracket) from the click event.
我如何扩展此代码以通常适用于所有带有class="test"
. 我的意思是点击元素并替换其内容。实际上,我们需要从单击事件中获取节点号(在括号内提供)。
I am trying to better understand javascript in unobtrusive codes, not a practical method like jQuery.
我试图在不显眼的代码中更好地理解 javascript,而不是像 jQuery 这样的实用方法。
回答by Blender
Just iterate over them:
只需迭代它们:
var elements = document.getElementsByClassName('test');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', (function(i) {
return function() {
this.innerHTML = 'New Text';
};
})(i), false);
}?
I used (function(i) { return function() { ... }; })(i)
instead of just function() { ... }
because if you happen to use i
in the callback, the value of i
will be elements.length - 1
by the time you call it. To fix it, you must shadow i
and make it essentially pass by value.
我使用(function(i) { return function() { ... }; })(i)
而不是仅仅function() { ... }
因为如果你碰巧i
在回调中使用,值i
将会在elements.length - 1
你调用它的时候。要修复它,您必须隐藏i
并使其基本上按值传递。
回答by Niet the Dark Absol
Just use this
inside the function. this
will be the element on which the event is being fired.
只需this
在函数内部使用。this
将是触发事件的元素。
(function() {
var elms = document.getElementsByClassName("test"),
l = elms.length, i;
for( i=0; i<l; i++) {
(function(i) {
elms[i].onclick = function() {
this.innerHTML = "New Text";
};
})(i);
}
})();
It's a bit more complicated than jQuery's:
它比 jQuery 复杂一点:
$(".test").click(function() {
$(this).html("New Text");
});
But it'll be significantly faster without the bloat that jQuery adds ;)
但是如果没有 jQuery 增加的膨胀,它会快得多;)
回答by Danilo Valente
var all = document.getElementsByClassName('test');
for(var i=0;i<all.length;i++)
all[i].onclick=function(){
this.innerHTML = 'New Text';
}
But it's most recommended to use addEventListener (or attachEvent, in IE/Some versions of Opera, I guess):
但最推荐使用 addEventListener (或 attachEvent,在 IE/Opera 的某些版本中,我猜):
var all = document.getElementsByClassName('test');
for(var i=0;i<all.length;i++)
all[i].addEventListener('click',function(){//If you're gonna use attachEvent, use 'onclick' instead of 'click'
this.innerHTML = 'New Text';
}});