jQuery .click() function called automatically

流过昼夜 提交于 2019-11-26 18:39:50

问题


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) {
    ...
    ...
}

回答1:


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




回答2:


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);
});


来源:https://stackoverflow.com/questions/17519373/jquery-click-function-called-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!