(function($)
{
$.vari = "$.vari";
$.fn.vari = "$.fn.vari";
// $.fn is the object we add our custom functions to
$.fn.DoSomethingLocal = function()
{
return this.each(function()
{
alert(this.vari); // would output `undefined`
alert($(this).vari); // would output `$.fn.vari`
});
};
})(jQuery);
// $ is the main jQuery object, we can attach a global function to it
$.DoSomethingGlobal = function()
{
alert("Do Something Globally, where `this.vari` = " + this.vari);
};
$(document).ready(function()
{
$("div").DoSomethingLocal();
$.DoSomethingGlobal();
});
我很困惑,为什么在$.fn.DoSomethingLocal
功能,$(this).vari
是字符串“$ .fn.vari”,而不是“$ .vari”混淆。我认为each
调用中的this
参考提供了一个dom对象,因此调用$(this)
将返回一个标准jquery对象,其原型为$
,而不是$.fn
。通过引用
这是怎么发生的?
不知道这是否是你问的,但你是否知道.each循环内的$(this)引用循环中的当前项? – treeface 2010-08-12 20:02:24