本文介绍了jQuery .click()函数自动调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery在按钮上设置了一个事件监听器,由于某种原因,在没有单击按钮的情况下调用click监听器中的函数。我知道通常函数在侦听器中是匿名的,但它不能用作匿名函数。我调用的函数也必须接受参数,这就是为什么我认为我不能只调用函数的引用。有关如何解决函数问题的任何想法,如果没有点击甚至注册,仍然将必要的参数传递给函数?

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

调用此函数

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


推荐答案

您正在错误地引用该功能。请尝试这样做:

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

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

每当使用语法 funcName()()告诉解释器立即调用该函数。 .click 方法要求您传递对函数的引用。函数引用仅按名称传递。你也可以这样做:

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

这篇关于jQuery .click()函数自动调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:34