如何获取getElementsByClassName中的当前元素 [英] How to get current element in getElementsByClassName
问题描述
考虑一个简单的JS事件
Consider a simple JS event of
document.getElementsByClassName('test')[0].onclick=function(){
document.getElementsByClassName('test')[0].innerHTML = 'New Text';
}
如何将此代码扩展为通常适用于<$ c的所有元素$ C>类= 测试。我的意思是点击元素并替换其内容。实际上,我们需要从click事件中获取节点号(在括号内提供)。
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.
我试图更好地理解不显眼的代码中的javascript,而不是实用的方法如jQuery。
I am trying to better understand javascript in unobtrusive codes, not a practical method like jQuery.
推荐答案
只需迭代它们:
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);
}
我用(function(i){return function(){...};})(i)
而不只是 function(){...}
因为如果你碰巧在回调中使用 i
, i
的值将是 elements.length - 1
到你打电话的时候。要解决此问题,您必须隐藏 i
并使其基本上按值传递。
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.
这篇关于如何获取getElementsByClassName中的当前元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!