How to get current element in getElementsByClassName

前端 未结 3 1828
暗喜
暗喜 2020-12-29 11:23

Consider a simple JS event of

document.getElementsByClassName(\'test\')[0].onclick=function(){
document.getElementsByClassName(\'test\')[0].innerHTML = \'New          


        
3条回答
  •  无人及你
    2020-12-29 11:49

    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.

提交回复
热议问题