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 badges
Add a ment  | 

4 Answers 4

Reset to default 7

You 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