javascript 点击功能触发页面加载?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7312562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:42:39  来源:igfitidea点击:

Click function firing on pageload?

javascriptjqueryjavascript-eventsonloadmouseclick-event

提问by Damon

Trying to figure out how this is possible...

试图弄清楚这是怎么可能的......

$(function() {
   $('#saveBtn').click(save());
});

function save(){
    alert('uh');
}

.

.

<form id="video-details" method="post" action="">
    <input id="saveBtn" class="submit" type="submit" name="submit" value="Submit Video" disabled/>
</form>

I set a breakpoint on the save() function and it is being called by an anonymous function on the line with the click event listed. However this is happening directly on load, not to mention that the input starts off invisible and disabled so there is no way to click it.

我在 save() 函数上设置了一个断点,它被一个匿名函数在列出了 click 事件的那一行调用。然而,这是在加载时直接发生的,更不用说输入开始时不可见且禁用,因此无法单击它。

I changed the click function to different elements that both exist and don't exist and whatever I make it the function still fires on pageload.

我将点击功能更改为存在和不存在的不同元素,无论我如何设置,该功能仍会在页面加载时触发。

Not sure where else to investigate the cause of this, but I'm assuming it's not normal behaviour

不知道还有什么地方可以调查这个原因,但我假设这不是正常行为

回答by detaylor

Try changing your script to:

尝试将您的脚本更改为:

$(function() {
   $('#saveBtn').click(save);
});

function save(){
    alert('uh');
}

By having brackets in the clickdeclaration you are calling the function. If you just use the function name then you are providing a reference to the function instead of a call.

通过在click声明中包含括号,您正在调用该函数。如果您只使用函数名称,那么您提供的是对函数的引用而不是调用。

Calling with variable

用变量调用

If you are calling the function with a variable you would need to make use of a closure (assuming that you have access to the variable when declaring the event

如果您使用变量调用函数,则需要使用闭包(假设您在声明事件时有权访问该变量

$(function(){
  var foo = 'bar';
  $('#saveBtn').click(
    function(){
      save(foo);
    });

function save(message){
  alert(message);
}

For more information on closures check out How do JavaScript closures work?.

有关闭包的更多信息,请查看JavaScript 闭包如何工作?.

回答by kmcc049

try changing to this. You are invoking click accidentally

尝试更改为这个。您不小心调用了 click

$(function() {
   $('#saveBtn').click(function (){
     save()});
});