jQuery中this和$(this)之间的区别:

this返回的是当前对象的html对象,而$(this)返回的是当前对象的jQuery对象

举个正确的Demo实例:

$("#textbox").hover(
    function() {
        this.title = "Test";
    },         
    fucntion() {             
        this.title = "OK”;         
    }   
 );
View Code

 以上的this为html元素即元素textbox,该元素有title属性,因此以上的程序没有错误。如果将以上的程序中this替换成$(this)时,该程序就会报错,因为$(this)返回的是一个jQuery对象,而jQuery对象是没有title这些属性的,而$(this)中有方法可以对html元素中title属性进行设置和修改。代码如下:

 $("#textbox").hover(
         function() {
            $(this).attr('title', 'Test');
         },         
        fucntion() {             
            $(this).attr('title', 'OK');         
        }   
 );
View Code

使用jQuery的好处是它包裝了各种浏览器版本对DOM对象的操作,因此统一使用$(this)而不再用this应该是比较不错的选择。

 

$.fn是指jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效。如扩展$.fn.test(),即$.fn.test()是对jquery扩展了一个test方法,那么后面你的每一个jquery实例都可以引用这个方法了。

jQuery为开发插件提拱了两个方法,分别是:jQuery.extend(object):为扩展jQuery类本身.为类添加新的方法和jQuery.fn.extend(object):给jQuery对象添加方法。

也就是说jQuery.extend(object)相当于扩展静态的方法,而jQuery.fn.extend(object)相当于扩展非静态的成员方法。

jQuery.extend(object)Demo实例代码如下:

$.extend({ 
  add:function(a,b){returna+b;} 
}); 
View Code

使用方法如下:$.add(3,4); //return 7

jQuery.extend()方法也可以用作合并对象,在合并对象时,第一个参数代表是否需要深合并。使用的原型为:jQuery.extend(bool,destObj,sourceObj)

jQuery.extend(bool,destObj,sourceObj1,sourceObj2,...)Demo实例代码如下:

var destObj={ 
    name: "destname", 
    location: {
        city: "destcicty",
        county:"destcountry"
    } 
};

var sourceObj={ 
    name: "sourcename1", 
    location: {
        city: "soucecity1",
        county:"sourcecountry1"
    } 
};

var sourceObj2={ 
    name: "sourcename2", 
    location: {
        city: "soucecity2",
        county:"sourcecountry2"
    } 
};

var result=$.extend(true,destObj,sourceObj1,sourceObj2);        //result=var sourceObj={ name: "sourcename2", location: {city: "soucecity2",county:"sourcecountry2"} }
View Code

jQuery.fn.extend(object)是对jQuery.prototype进得扩展,jQuery类的实例可以使用这个“成员函数”。 Demo实例代码如下:

$.fn.extend({ 
    alertWhileClick: function(){ 
        $(this).click(function(){ 
            alert($(this).val()); 
        }); 
    } 
}); 
View Code

 

posted on 2014-11-14 22:38  边城愚者  阅读(1399)  评论(0编辑  收藏  举报