简体   繁体   中英

How to pass a parameter in an onclick function?

I would like to use an onclick function which takes a parameter in JavaScript.

Calling button.onclick = someAction works. Is there a way to use a function that takes parameter(s) instead? For example:

function loadAPP() {
    button = someButton(param);
    button.onclick = someAction(param);
    document.body.appendChild(button);
}

You can use bind and bind the parameter to your function.

 const someAction = param => console.log(param); const button = document.createElement('button'); button.onclick = someAction.bind(button,'this is my params'); document.body.appendChild(button); 

The easiest way I know is include the value in data-* attributes and call it inside the click event function

 var btn = document.getElementById("test"); btn.onclick = function(){ console.log(btn.getAttribute("data-param1")); console.log(btn.getAttribute("data-param2")); } 
 <button id="test" data-param1="value1" data-param2="value2"> Test </button> 

Standard practice is to use an anonymous function :

button.onclick = () => someAction(param);

or

button.onclick = function() { someAction(param) };

if your environment doesn't support arrow syntax.

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