jQuery this揭秘
Example of this as a DOM element
'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.
this在jQuery的回调函数,如click,each, bind等方法时是一个DOM元素。
$('a.newTarget').each(function() { // <- our anonymous callback
// check the DOM attribute 'host' on this
if (this.host != window.location.host) {
// create a jQuery object using the current DOM element
$(this).attr('target', '_new');
}
});
Example of this as a jQuery object
'this' is a jQuery object when you are inside your own jQuery functions. Note that the result of a selector query (i.e. $('a') ) is a jQuery object, which is an array of the matched DOM elements(imagine jQuery is an array with bells on).
当this用于你自己的jQuery对象时,this是一个jQuery对象。
注: 一个选择器查询,如$('a')的结果是一个jQuery对象,其实是由一组DOM元素组成的数组。
jQuery.fn.newTarget = function() {
// 'this' is a jQuery object at this point - with all the jQuery functions
return this.each(function() { // return so we don't break the chain
// now we are inside of a jQuery function, the DOM element is the context
// so 'this' has changed to become a DOM element.
if (this.host != window.location.host) {
$(this).attr('target', '_new');
}
});
};
Finishing up
结束语
This is far from comprehensive, but equally there's very little to the logic. So long as you remember the context of 'this' changes when moving in and out of object methods then you're on your way.
以上远不足以使你理解jQuery中this的用法。但是只要当你move int and out of 对象时谨记this改变的上下文,then you're on your way.
If you're still not sure, get your hands on Firebug and add 'console.log(this)' within your code to interrogate and understand what 'this' is at that point in your code.
如果你仍不确信,使用Firebug,添加‘console.log(this)’到你的代码中来查询并理解当前位置的this的含义。