简体   繁体   中英

assign onclick event to several DOM elements at the same time

Is it possible to set the same onclick event to all elements of the same class / tag / etcetera? The following code does not work.

document.getElementsByTagName("A").onclick = function(){alert("!")};

Yes you can loop each element and assign your listener

var elements = document.getElementsByTagName("a");
for(var i=0; i<elements.length; ++i) {
    elements[i].addEventListener("click", function(event) {
        alert(elements[i].nodeValue);
    }, false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM