gpt4 book ai didi

javascript - 事件处理程序中的调用函数

转载 作者:行者123 更新时间:2023-12-01 02:21:08 25 4
gpt4 key购买 nike

我用 JavaScript 代码编写了两个函数,如下

Manager = FormManager.extend({
First: function () {
var response = this.Second("Feature"); //I'm able to get the alert

//I have added a click event handler
$('#element').on('click', function(){
var newResponse = this.Second("Bug"); //The alert is not poping
});

}

Second: function (type) {
alert(type);
//Performs certain operation
}
});

Error: Uncaught TypeError: Object #<HTMLButtonElement> has no method 'Second'

我也尝试过不使用 this 关键字,例如:

Second("Bug") // Error: There is no method

这是我正在使用的程序上的简化格式(为了显示一个简单的示例)。我正在努力找出原因。

有人可以引导我走上正确的道路吗?

最佳答案

您使用的不正确。试试这个方法。处理程序内的 this 代表 #element 而不是函数本身的上下文。

 var self = this; //cache the context here
$('#element').on('click', function(){
var newResponse = self.Second("Bug"); //Access it with self
});

此外,我认为您在 First 函数定义之后和 Second 函数之前缺少一个逗号。

<强> Fiddle

原因是您给出的回调是从元素的上下文中调用的,因此您的 this 上下文发生了变化。 this 上下文是指调用回调的上下文。但还有其他方法可以解决这个问题,例如使用 $.proxy在将回调与 jquery 绑定(bind)时,使用 EcmaScript5 Function.prototype.bind等等。但理想情况下您不想这样做,因为大多数情况下您需要处理程序内元素的上下文。

关于javascript - 事件处理程序中的调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18925350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com