如何在引用jQuery对象的函数中获取'this'

时间:2014-03-10 15:17:25

标签: javascript jquery this

除此之外,我读过:

但他们还没有解决我使用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的引用传递给函数。我知道showSectionhideSection函数被触发 - 我无法让这些函数中的this引用sections数组中的jQuery对象。

我尝试了上述的多种变体(call除外,在函数中使用$(this),将showSectionhideSection函数添加到jQuery对象中 - 其中其他)但我有点想法 任何帮助非常感谢!

2 个答案:

答案 0 :(得分:1)

事件处理程序中的

this是事件绑定到的元素节点。如果您想要一个包装该节点的jQuery对象,请使用$(this)

演示:http://jsfiddle.net/b36M6/

这当然假设您恢复到将函数传递给事件绑定的正确方法。

答案 1 :(得分:0)

当您使用.call()时,您将立即调用该函数。

由于你希望this引用元素,绑定,只需通过函数本身。

sections[sections.length-1].on('show', this.showSection);
sections[sections.length-1].on('hide', this.hideSection);

现在thisshowSection方法中的hideSection将引用它所绑定的sections[]成员。

我认为"show""hide"是某种自定义事件。