Pass arguments to a callback function in jquery cl

2019-04-28 19:14发布

This question already has an answer here:

Straight to the business:

I have a jquery event listener that looks like this:

$(".number").click(printNumber);

and a callback function:

function printNumber(number){
   console.log(number);
}

I was wondering if I could pass an argument to a callback so it will look something like this

$(".number").click(printNumber(number));

(I know that it immediately invokes that function, but still, is there a way to pass arguments to it)

Thank you in advance!

2条回答
不美不萌又怎样
2楼-- · 2019-04-28 19:29

You can pass data to the callback directly as event.data in jQuery

$(".number").on('click', {number : 4}, printNumber);

function printNumber(event){
   console.log(event.data.number); // 4
}

Another way would be to use bind

$(".number").click(printNumber.bind($, 4));

function printNumber(number, event){
   console.log(number); // 4
}

But that would also change the callbacks this value

查看更多
再贱就再见
3楼-- · 2019-04-28 19:45

The clean way to handle this is to return a function:

function printNumber(number) {
   return function(e) {
       console.log(number);
   };
}

And then use:

$(".number").click(printNumber(number));
查看更多
登录 后发表回答