简体   繁体   中英

How can i pass parameters to a function inside click eventlistner

function changeColor(btn){
    btn.style.backgroundColor = "red";
}
let btn1 = document.getElementById("1");
btn1.addEventListener("click",changeColor(btn1));

I know that calling a function in the " addEventListner " immediately call the function. But I do need to pass a object to my function inside " addEventListner() " because I'm planning to use only one general function to handle clicks of 10 buttons.

You have to create an anonymous function () => changeColor(btn)

function changeColor(btn){
    obj.style.backgroundColor = "red";
}
let btn1 = document.getElementById("1");
btn1.addEventListener("click", () => changeColor(btn));

From the above comment...

"A handler function gets passed an Event type to it. An UI event always features a currentTarget and a target property. The OP should access the former... event.currentTarget.style.backgroundColor = "red"; ."

Instead of using the color changing function as callback one could implement a button specific click handler which forwards its current target to a generic function which changes the background color of any passed element reference.

 function changeElementColor(elm){ elm.style.backgroundColor = 'red'; } function handleButtonClick(evt) { changeElementColor(evt.currentTarget); } document.querySelectorAll('button').forEach(btnElm => btnElm.addEventListener('click', handleButtonClick) );
 <button><em>Hallo</em></button> <button><b>World</b></button>

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