How to get current element in getElementsByClassName

跟風遠走 提交于 2019-11-29 02:54:29

问题


Consider a simple JS event of

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.

I am trying to better understand javascript in unobtrusive codes, not a practical method like jQuery.


回答1:


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.




回答2:


Just use this inside the function. this will be the element on which the event is being fired.

(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:

$(".test").click(function() {
    $(this).html("New Text");
});

But it'll be significantly faster without the bloat that jQuery adds ;)




回答3:


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):

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';
    }});


来源:https://stackoverflow.com/questions/11075819/how-to-get-current-element-in-getelementsbyclassname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!