开发者

How to call a javascript-delegate with parameters?

Lets say I have a javascript function call moveItem which ta开发者_Go百科kes two parameters source and destination.

I want to assign this function the the click-event of several buttons, each having different source and destinations.

OK, so without the parameter I would do something like this:

$('#myButton1').click(moveItem);

function moveItem() {
...
}

But what if moveItem looks like this:

function moveItem(source, destination) {
...
}

this doesn't seem to work:

$('#myButton1').click(moveItem('foo','bar'));


You can't do quite what you want. You'll have to use an anonymous function to call moveItem:

$('#myButton1').click(function(){ moveItem('foo','bar'); };

When registering functions for events, the function signature has to match one of the supported signatures (because code in the click function is calling the handler). Since moveItem doesn't match, you have to wrap it in an anonymous function that does match.


You want to do

$('#myButton1').click(function() {moveItem('foo','bar')});


$('#myButton1').click(function(){moveItem(source, destination)});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜