除此之外,我读过:
但他们还没有解决我使用JavaScript的“这个”问题。
我有一个Section对象,它传递了一些XML,用于填充该部分。在Section对象中,我追加一个具有指定索引的div
。生成的jQuery对象被推送到sections
数组中。以下代码来自Section对象代码:
sections.push($('#section' + p_sectionIndex));
this.showSection = function() {
this.show();
}
this.hideSection = function() {
this.hide();
}
sections[sections.length-1].on('show', this.showSection.call(sections[sections.length-1]));
sections[sections.length-1].on('hide', this.hideSection.call(sections[sections.length-1]));
在其他地方,我致电sections[index].trigger('hide');
和sections[index].trigger('show');
我上面提到的第一个链接似乎暗示函数中的this
取决于它被调用的方式,并且您可以使用this
将对call
的引用传递给函数。我知道showSection
和hideSection
函数被触发 - 我无法让这些函数中的this
引用sections
数组中的jQuery对象。
我尝试了上述的多种变体(call
除外,在函数中使用$(this)
,将showSection
和hideSection
函数添加到jQuery对象中 - 其中其他)但我有点想法
任何帮助非常感谢!
答案 0 :(得分:1)
this
是事件绑定到的元素节点。如果您想要一个包装该节点的jQuery对象,请使用$(this)
这当然假设您恢复到将函数传递给事件绑定的正确方法。
答案 1 :(得分:0)
当您使用.call()
时,您将立即调用该函数。
由于你希望this
引用元素,绑定,只需通过函数本身。
sections[sections.length-1].on('show', this.showSection);
sections[sections.length-1].on('hide', this.hideSection);
现在this
和showSection
方法中的hideSection
将引用它所绑定的sections[]
成员。
我认为"show"
和"hide"
是某种自定义事件。