jquery从父级引用它 [英] jquery reference this from parent
本文介绍了jquery从父级引用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Google试图找到这个问题的答案并没有帮助! :(
Google is not being helpful trying to find the answer to this question! :(
如何从jQuery函数中的父对象正确引用 this.colour
,如下所示:
How do I properly reference this.colour
from the parent object from within a jQuery function like this:
var obj = {
colour: 'blue',
do: function() {
$.getJSON('getcolour.php', function(resp) {
if (resp.colour == this.colour) { //<== this.colour doesnt = blue
//match
}
});
}
}
推荐答案
您需要获取对此
外的引用 $。getJSON
:
do: function() {
var self = this;
$.getJSON('getcolour.php', function(resp) {
if (resp.colour === self.colour) { // use "self"
// ...
}
});
}
,在ES5浏览器上,使用 .bind
将内部回调的上下文设置为此
:
alternatively, on ES5 browsers, use .bind
to set the context of the inner callback to this
:
do: function() {
$.getJSON('getcolour.php', function(resp) {
if (resp.colour === this.colour) {
// ...
}
}).bind(this); // set the callback's context
}
jQuery的 $。代理()
函数也可用于早期的浏览器,以达到同样的效果。
jQuery's $.proxy()
function can also be used on earlier browsers to achieve the same effect.
这篇关于jquery从父级引用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文