jQuery .click() function called automatically

2019-01-12 13:01发布

I have an event listener set up on a button using jQuery, and for some reason the function within the click listener is called without the button being clicked. I know that usually functions are anonymous in listeners, but it won't work as an anonymous function. The function I am calling also has to accept parameters, which is why I don't think I can just call a reference to the function. Any ideas on how I can fix the problem of the function getting called without a click even registered and still pass the necessary parameters to the function?

$('#keep-both').click(keepBothFiles(file, progress, audioSrc));

calls this function

function keepBothFiles(file, progress, audioSrc) {
    ...
    ...
}

2条回答
劳资没心,怎么记你
2楼-- · 2019-01-12 13:16

You're referencing the function incorrectly. Try this instead:

$('#keep-both').click(function(){
  keepBothFiles(file, progress, audioSrc));
});

Whenever you use the syntax funcName(), the () tell the interpreter to immediately invoke the function. The .click method requires that you pass it a reference to a function. Function references are passed by name only. You could also do:

$('#keep-both').click(keepBothFiles);

But you can't pass it your other arguments. It's given an event object by default

查看更多
欢心
3楼-- · 2019-01-12 13:24

You must pass a function reference to the .click() function, not the result of calling a function. When you include the () like this keepBothFiles(...) at the end of the function name, you are telling javascript to execute the function now. When you just use the name of the function like keepBothFiles, you are getting a reference to the function (which can be called later).

You are currently calling your function immediately and then passing the return value of that function (which is not a function reference) to the .click() function, thus it does not do what you want.

The click handler callback function is passed exactly one parameter (the event) in jQuery so you cannot have it call your keepBothFiles(file, progress, audioSrc) function directly like you have it.

Instead, it could be done like this with a second wrapper function:

$('#keep-both').click(function(e) {
    keepBothFiles(file, progress, audioSrc);
});
查看更多
登录 后发表回答