gpt4 book ai didi

javascript - 面向对象的 jquery - 事件处理程序不起作用

转载 作者:行者123 更新时间:2023-12-03 04:18:22 25 4
gpt4 key购买 nike

我正在将一些 jquery 函数移动到 javascript 对象中以清理一些代码。我的问题是,当我将方法放在对象的构造函数上时,我的事件处理程序似乎不响应事件,但如果我的处理程序是辅助方法并且位于对象的构造函数之外,则响应良好。

这是我的代码,不起作用

function MyConstructor() {
this.init();
this.selectAllHandler();
}

MyConstructor.prototype = {
init: function() {
$(document).on('click', '#my_element', this.selectAllHandler);
},
selectAllHandler: function() {
// some code in here
}
}

使用此功能时,我的代码不会出错并将 console.log 放在函数运行的顶部。但是,当我尝试单击该事物来触发处理程序时,它不会执行任何操作。

但是,如果我使用对象外部的方法将其构建为构造函数,则它可以正常工作。像这样

function MyConstructor() {
this.init();
}

MyConstructor.prototype = {
init: function() {
$(document).on('click', '#my_element', selectAllHandler);
}
}

function selectAllHandler() {
// code that works fine
}

我做错了什么,无法调用对象原型(prototype)内的处理程序?

编辑

这是我的新代码。现在的问题是 $(this) 似乎指的是构造函数,而不再指的是被单击的元素。

function MyConstructor() {
this.init();
}

MyConstructor.prototype = {
init: function() {
$(document).on('click', '#my_element', this.selectAllHandler.bind(this));
},
selectAllHandler: function() {
var checkboxes = $('.prospect_select_box');

console.log($(this)); // => [MyConstructor]

if (!$(this).prop('checked')) {
console.log('here')
checkboxes.prop('checked', false);
$('#prospect-left-section').hide();
} else {
console.log('other here')
checkboxes.prop('checked', true);
$('#prospect-left-section').show();
}
}
}

最佳答案

您有两个感兴趣的对象:构造的对象和单击的元素。第一个需要找到方法 selectAllHandler,第二个需要在该函数中使用 $(this)。显然,它们不能同时是 this,因此您需要以不同的方式引用其中一个。

以下是您可以如何做到这一点。

function MyConstructor() {
this.init();
}

MyConstructor.prototype = {
init: function() {
var that = this;
$(document).on('click', '#my_element', function () {
that.selectAllHandler.call(this);
});
},
selectAllHandler: function() {
$(this).text('clicked!');
}
}

new MyConstructor();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="my_element">click me</button>

请注意如何使用 call 来确保 selectAllHandler 将在 this 设置为 jQuery 作为元素传递的内容的情况下运行。

但是,如果您还需要使用 this inside setAllHandler 引用构造对象,则以相反的方式执行,并使用作为 this,但通过传递给函数的事件对象引用单击的元素:

function MyConstructor() {
this.init();
}

MyConstructor.prototype = {
init: function() {
var that = this;
$(document).on('click', '#my_element', this.selectAllHandler.bind(this));
},
selectAllHandler: function(e) {
var elem = e.target;
$(elem).text('clicked ' + this.other);
},
other: 'me!'
}

new MyConstructor();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="my_element">click me</button>

关于javascript - 面向对象的 jquery - 事件处理程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44054133/

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