gpt4 book ai didi

javascript - 事件监听器不绑定(bind)

转载 作者:行者123 更新时间:2023-11-29 21:51:33 25 4
gpt4 key购买 nike

我希望有人能够告诉我为什么调用 TestProtObj.init 没有按预期工作——监听器没有全部工作。

$(document).ready(function () {
//set TestProtObj properties in the constructor
var TestProtObj = function (string, target, button) {
this.testValue = string;
this.target = $(target);
this.button = $(button);
}

//add methods to the object prototype
TestProtObj.prototype = {

init: function () {
this.button.on('click', function (e) {
e.preventDefault;
this.returnTest();
});
},

returnTest: function () {
this.target.append(this.testValue);
}
}

//initialize client code
var testString = 'It worked!',
targetDiv = '#target',
button = 'button.text-button';
//call the returnTest() method and pass in params above
var TestConcObj = new TestProtObj(testString, targetDiv, button);
TestConcObj.init();
});

奇怪的是,下面的代码有效:

$(document).ready(function () {
var bindListener = function () {
$('.test').on('click', function (e) {
e.preventDefault;
$('.target').append('It works!');
})
}

bindListener();
})

似乎将函数放入对象字面量是出于某种原因,导致它失败。 Chrome 调试工具栏中未抛出任何错误。

非常感谢帮助。

JSFiddles:

#1 #2

最佳答案

只需在该函数内创建一个私有(private)变量,它使用关键字this 引用init 函数内的TestProtObj。您可以在函数 init 的整个范围内重复使用此变量 (self)。

    init: function () {
var self = this;
this.button.on('click', function (e) {
e.preventDefault(); //add () here.
self.returnTest();
});

因为 JavaScript 使用 lexical scope这会起作用。

https://jsfiddle.net/p9fjamz3/14/

当您在事件处理程序中引用 this 时 this.button.on('click', ... 您实际上指的是按钮而不是您的对象。

关于javascript - 事件监听器不绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28883213/

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