Javascript:通过对象函数内的点击函数调用对象函数
问题描述:
我遇到问题。这是我第一次尝试在Javascript中使用对象,并且遇到问题。Javascript:通过对象函数内的点击函数调用对象函数
我有一个对象,其中包含一个DOM元素,我想添加到该元素的子元素点击功能。在点击函数内部,我想调用另一个对象函数,但这不起作用。要调用另一个对象函数,我必须使用this.functionname()
,但因为我在点击函数this
中不再是我的对象,而是添加了点击函数的子元素。所以我的问题是:如何从点击函数内部调用我的对象函数。
这是我的代码(在代码中的中间的,如果条件是不重要的):
function ManagementCard(card) {
this.card = card;
this.row = null;
this.rowAlt = null;
this.managementCard = this;
}
ManagementCard.prototype.initializeCard = function() {
this.card.find(".card ul li div:first-child").click(function() {
row = $(this).parent();
if(this.rowAlt != null && this.rowAlt[0] != $(this).parent()[0])
{
this.rowAlt.children("div:last-child").collapse('hide');
$(this.rowAlt).css('background-color', '');
$(this.rowAlt).css('color', '');
this.rowAlt = null;
}
this.toggleManagementRow(); <=== Important! Call object-function from inside of a click-function which is inside the object-function
});
}
ManagementCard.prototype.getCard = function() {
return this.card;
}
答
保持参考物体在另一个变量例如self
。它是这样做在JavaScript
ManagementCard.prototype.initializeCard = function() {
var self = this;
this.card.find(".card ul li div:first-child").click(function() {
row = $(this).parent();
if(this.rowAlt != null && this.rowAlt[0] != $(this).parent()[0])
{
this.rowAlt.children("div:last-child").collapse('hide');
$(this.rowAlt).css('background-color', '');
$(this.rowAlt).css('color', '');
this.rowAlt = null;
}
self.toggleManagementRow();
});
}
非常感谢你:)简单的解决方案 – kruben
不只是接受的解决方案,请阅读并试图理解为什么它的工作原理 – mic4ael
不用担心常见的事,我明白为什么:) 再次感谢 – kruben