如何获得'this'在一个引用jQuery对象的函数中
How to get 'this' in a function referring to jQuery object
我读过:
- 这是什么意思
- 你肯定也记得这
- 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
的引用传递到函数中。我知道showSection
和hideSection
函数正在被触发-我只是不能在这些函数中获得this
来引用sections
数组中的jQuery对象。
我已经尝试了以上的多种变体(不包括call
,在函数中使用$(this)
,将showSection
和hideSection
函数添加到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);
现在showSection
和hideSection
方法中的this
将指向其绑定的sections[]
成员。
我假设"show"
和"hide"
是某种自定义事件
- jQuery引用创建的元素
- 将 jQuery 引用放在母版页有什么好处
- jQuery - 引用同一对象的另一个类
- 将 jQuery 引用移动到 asp.net 母版页时出现 Java 脚本错误
- 使用jQuery引用嵌套的HTML元素
- 如何使jquery引用动态html元素
- 使用jquery引用javascript变量时出现问题
- 使用 jQuery 引用 html 输入元素
- JQuery引用变量带有选择器,数据错误
- 如何在javascript文件中添加jquery引用
- 触发调用的表单的jQuery引用
- Jquery:引用js文件中的DOM准备函数
- 使用jquery引用动态内容
- JQuery引用错误(Safari特有)
- 在事件触发时通过生成的HTML生成JQuery引用
- jquery引用错误,同时获得两个版本的jquery
- 为什么我的jQuery引用不起作用?我引用的脚本不正确
- c# Jquery引用错误未定义
- 使用jQuery引用同一对象中的另一个变量
- jQuery引用问题与函数在OnClick