I'm trying to pass an parameter to an anonymous function. But Something is wrong and I cannot figure it out.
function getInfo(item) { alert(item); //does not pass the item? } var param = "Param was passed successfully!"; var elementel = document.getElementById("AlretBtn"); elementel.addEventListener("click", getInfo.bind(null, param, false);
<button id="AlretBtn">Alert Item</button>
What's wrong with this? How can I fix this?
function getInfo(item) { alert(item); //does not pass the item? } var param = "Param was passed successfully!"; var elementel = document.getElementById("AlretBtn"); elementel.addEventListener("click", getInfo.bind(null, param, false));
<button id="AlretBtn">Alert Item</button>
You are missing a parenthesis. I don't know if you are using an IDE, or what is your development environment. But, try to add a javascript syntax validator, it really makes development so much faster :)
I'm not sure what you intend to do, but you're not binding anything to getInfo(). In case you wanted to bind the click handler to the button element:
function getInfo(item){
alert(item); //does not pass the item?
console.log(this); // the button element instead of Window
}
var param = "Param was passed successfully!";
var elementel = document.getElementById("AlretBtn");
elementel.addEventListener("click", getInfo.bind(elementel, param, false));
And in case you don't need to bind the click handler to it, why bother with bind()?:
function getInfo(item){
alert(item); //does not pass the item?
}
var param = "Param was passed successfully!";
var elementel = document.getElementById("AlretBtn");
elementel.addEventListener("click", function(){ getInfo(param); });
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.