When I assign the event handler without parameters, it works: /
function show(){
alert('work');
}
var myButton = document.createElement("input");
myButton.type="button";
myButton.value="click";
myButton.onclick=show;
var where = document.getElementById("where");
where.appendChild(myButton);
but if I pass parameters, it doesn't work: /
myButton.onclick = show('test');
How can I use function with parameters in dynamically created elements?
When I assign the event handler without parameters, it works: http://jsfiddle/mUj43/
function show(){
alert('work');
}
var myButton = document.createElement("input");
myButton.type="button";
myButton.value="click";
myButton.onclick=show;
var where = document.getElementById("where");
where.appendChild(myButton);
but if I pass parameters, it doesn't work: http://jsfiddle/mUj43/1/
myButton.onclick = show('test');
How can I use function with parameters in dynamically created elements?
Share Improve this question edited Aug 19, 2012 at 15:49 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked Aug 19, 2012 at 15:05 mietexmietex 353 bronze badges4 Answers
Reset to default 7You can't do that, you could use partial application by creating a new function and then attach that as event handler:
myButton.onclick=show.bind( myButton, 'test');
http://jsfiddle/mUj43/2/
Docs (which I remend you read because this function is useful for many other things as well) and patibility information: https://developer.mozilla/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
You'll have to create your own closure:
myButton.onclick = function () {
show.call(this, 'test');
};
You could also use @Esailija's bind
method, but this one has deeper browser support.
try:
myButton.onclick = function(){show("test");}
or :
myButton.onclick = function(){ show.call( this, "test");}
if you want to retain the element object context inside the show function
That's because when you add events you need a function reference.
In your first example, show
is a reference to a function.
In your second example, show('test')
is a call to the function show
, which returns nothing, and nothing isn't a function reference.
That's why when you load the page, it alerts "work" (the function is called), but when you click the button no function is called.
Then, you need a function.
You can declare it:
myButton.onclick=f;
function f(){
show('test')
}
Or you can use an anonymous one:
myButton.onclick=function(){
show('test')
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742334589a4424396.html
评论列表(0条)