admin管理员组文章数量:1333385
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')
}
本文标签: javascriptEvent handler with parameters in dynamically created elementsStack Overflow
版权声明:本文标题:javascript - Event handler with parameters in dynamically created elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742334589a2455371.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论