[英]JavaScript function is called before clicking button
I have jsfiddle code. 我有jsfiddle代码。 What I am is I have an Cal
object which consists of init
function and another object called Event
. 我的意思是我有一个Cal
对象,该对象包含init
函数和另一个称为Event
对象。 Inside Event
I have two functions init
and show
. 在Event
内部,我有两个函数init
和show
。 What I am doing is calls init
function of Cal
object and passing parameter in there. 我正在做的是调用Cal
对象的init
函数并在其中传递参数。 Inside this init
function I am calling Event
's init
function and passing that same parameter here. 在此init
函数内部,我将调用Event
的init
函数,并在此处传递相同的参数。 and inside this init
function I am calling show
function inside Event
when user clicks on .button
link which shows param
in the console. 在此init
函数内部,当用户单击.button
链接(在控制台中显示param
时,我在Event
内部调用show
函数。 But when I run this code, it shows param
in the console before clicking .button
. 但是,当我运行此代码时,在单击.button
之前,它将在控制台中显示param
。 Why and how can I make it work so that it shows param when I click on .button? 为什么以及如何使它工作,以便在单击.button时显示参数?
Here is my code 这是我的代码
var Cal = {
init: function (param) {
this.param = param;
Cal.Event.init(this.param);
},
func: function () {},
Event: {
init: function (param) {
$('.button').on('click', this.show(param));
},
show: function (param) {
console.log(param);
}
}
}
Cal.init('para');
.on() expect parameter 2 to be a function, not the return value of that function .on()期望参数2是一个函数,而不是该函数的返回值
$('.button').on('click', function() {
// Here this points to the button DOM object.
Cal.Event.show(param)
});
In this line of code: 在这行代码中:
init: function (param) {
$('.button').on('click', this.show(param));
},
You're calling the show
function and then passing its return value into on
, so it runs when you call Cal.Event.init
. 您正在调用 show
函数,然后将其返回值传递给on
,因此它在您调用Cal.Event.init
时运行。 You're not giving on
code to call when the click occurs. 你不给on
代码时发生点击呼叫。 To do that, put it in an event handler function: 为此,将其放在事件处理程序函数中:
init: function (param) {
$('.button').on('click', function() {
Cal.Event.show(param);
});
},
Note that I changed this
to Cal.Event
because within the call to the handler function, this
will be a reference to the button, not Cal.Event
. 请注意,我改变了this
以Cal.Event
因为调用处理函数内, this
将是该按钮,而不是一个参考Cal.Event
。
You call this.show(param)
immediately. 您立即调用this.show(param)
。 Change it to this: 更改为此:
init: function (param) {
$('.button').on('click', $.proxy(function() {
this.show(param);
}, this));
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.