简体   繁体   中英

Pass parameter to function with addEventListener

I have an anonymous function

function getStocks(item){
   alert(item);
}

Below is my click event listener.

document.getElementById("passBtn").addEventListener("click", getStocks, false);

I need to pass a parameter to getStocks() . I tried the below but does not work. What's wrong?

document.getElementById("passBtn").addEventListener('click', function(){
  getStocks(item);
}, false);

Use the javascript bind function:

var item = "item";
document.getElementById("passBtn").addEventListener("click", 
    getStocks.bind(null, item), false);

See the above code in action, here: fiddle

See more information, here: Function.prototype.bind()

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