如何获得'this'在一个引用jQuery对象的函数中

How to get 'this' in a function referring to jQuery object

本文关键字:jQuery 引用 对象 一个 函数 this 何获得      更新时间:2023-09-26

我读过:

  • 这是什么意思
  • 你肯定也记得这
  • mythical-methods

但他们还没有解决'这个'问题,我有一块JavaScript。

我有一个Section对象,它传递了一些XML,它用来填充Section。在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取决于它的调用方式,并且可以通过使用call将对this的引用传递到函数中。我知道showSectionhideSection函数正在被触发-我只是不能在这些函数中获得this来引用sections数组中的jQuery对象。

我已经尝试了以上的多种变体(不包括call,在函数中使用$(this),将showSectionhideSection函数添加到jQuery对象中-等等),但我有点没有想法。
任何帮助非常感激!

事件处理程序中的

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

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

当然,这需要您恢复到将函数传递给事件绑定的正确方式。

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

因为你想让this引用元素,绑定,只需传递函数本身。

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

现在showSectionhideSection方法中的this将指向其绑定的sections[]成员。

我假设"show""hide"是某种自定义事件