简体   繁体   English

函数的范围作为 .click jQuery 选择的变量属性

[英]Scope of a function as variable attribution to a .click jQuery selection

The script in JavaScript/jQuery : JavaScript/jQuery 中的脚本:

// Creation of the variables

var foo = [];
foo.functionForClick = function(){ alert('foo'); }

var bar = [];
bar.functionForClick = function(){ alert('bar'); }

// Attribution of the function to the button
var button;

// button foo 
button = foo;
$('#buttonFoo').click(function(){button.functionForClick()});

// button bar, I MUST use the same 'button' variable, 
// it's in the script (it's in a for loop...)  
button = bar;
$('#buttonBar').click(function(){button.functionForClick();});

HTML code HTML代码

<button id="buttonFoo">
Show Foo
</button>

<button id="buttonBar">
Show Bar
</button>

Why, after execution of the script (which reproduces a more complicated script of a web app I'm coding), the "Show Foo" button alert "bar"?为什么在执行脚本(它重现了我正在编写的 Web 应用程序的更复杂脚本)后,“显示 Foo”按钮提醒“栏”?

Any solution?有什么解决办法吗?

You can have a look of the problem here:您可以在这里查看问题:

https://jsfiddle.net/hdye648f/ https://jsfiddle.net/hdye648f/

Yes.是的。 button.functionForClick is already a function, so no need to wrap it in the anonymous function. button.functionForClick 已经是一个函数,所以不需要将它包装在匿名函数中。 The extra anonymous function is causing button to be resolved when the function executes, rather than when the function is defined.额外的匿名函数导致button在函数执行时被解析,而不是在函数被定义时。

Instead of而不是

$('#buttonFoo').click(function(){button.functionForClick()});

do

$('#buttonFoo').click(button.functionForClick);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM