Use AddEventListener To Replace Each OnClick
I have unordered lists below for fruits, animals, trees....about 100 buttons with same class:
Solution 1:
Yes, you can do it :
var bbs = document.getElementsByClassName("bb");
for(var i =0; i< bbs.length; i++){
bbs[i].addEventListener('click', function(){
var attr = this.value;
console.log(attr);
});
}
<ul>
<li><button class="bb" value="apple" >Apple</button></li>
<li><button class="bb" value="banana">Banana</button></li>
<li><button class="bb" value="cherry">Cherry</button></li>
</ul>
Instead of console.log(attr);
you can call your custom function
Solution 2:
try that :
window.addEventListener( 'load' , function () {
var list = document.querySelectorAll( 'ul > li > button' );
for ( var i = 0 , l = list.length ; i < l ; i++ ) {
list[ i ].addEventListener( 'click' , function () {
aJax( this.value );
} );
}
} );
Solution 3:
the simplest way (no loops needed)
var container = document.querySelector("ul");
container.addEventListener("click", doSomething, false);
function doSomething(e) {
if (e.target !== e.currentTarget) {
var clickedItem = e.target.value;
console.log(clickedItem);
}
e.stopPropagation();
}
<ul>
<li><button class="bb" value="apple" >Apple</button></li>
<li><button class="bb" value="banana">Banana</button></li>
<li><button class="bb" value="cherry">Cherry</button></li>
</ul>
check this awesome article, I'm pretty sure it's what you're looking for Handling Events for Many Elements
Solution 4:
While other answers are right, if your list is long, you might delegate the click to the ul
element :
function logValue(evt){
let target = evt.target;
// only console.log if the click target has class "bb"
if(target.classList.contains("bb")){
console.log(target.value)
}
}
// wait for the document to be loaded
window.addEventListener("load",()=>{
let list = document.querySelector(".my-list");
if(list){
//delegate click handler to the <ul> element
list.addEventListener("click", logValue);
}
});
<ul class="my-list">
<li><button class="bb" value="apple">Apple</button></li>
<li>Banana
<ul>
<li><button class="bb" value="green_banana">Green_banana</button></li>
<li><button class="bb" value="yellow_banana">Yellow Banana</button></li>
</ul>
</li>
<li><button class="bb" value="cherry">Cherry</button></li>
</ul>
Post a Comment for "Use AddEventListener To Replace Each OnClick"