JQuery this和$(this)的区别及获取$(this)子元素对象的方法

1.JQuery this和$(this)的区别

相信很多刚接触JQuery的人,很多都会对$(this)和this的区别模糊不清,那么这两者有什么区别呢?

       首先来看看JQuery中的  $()  这个符号,实际上这个符号在JQuery中相当于JQuery(),即$(this)=jquery();也就是说,这样可以返回一个jquery对象。那么,当你在网页中alert($('#id'));时,会弹出一个[object Object ],这个object对象,也就是jquery对象了。

       那么,我们再回过头来说$(this),这个this是什么呢?假设我们有如下的代码:

$("#desktop a img").each(function(index){

            alert($(this));

            alert(this);

}

那么,这时候可以看出来:

alert($(this));  弹出的结果是[object Object ]

alert(this);        弹出来的是[object HTMLImageElement]

也就是说,后者返回的是一个html对象(本例中是遍历HTML的img对象,所以为HTMLImageElement)。

很多人在使用jquery的时候,经常this.attr('src');   这时会报错“对象不支持此属性或方法”,这又是为什么呢?其实看明白上面的例子,就知道错在哪里了:很简单,this操作的是HTML对象,那么,HTML对象中怎么会有val()方法了,所以,在使用中,我们不能直接用this来直接调用jquery的方法或者属性。

 

2.获取$(this)子节点对象的方法:find(element)

明白了$(this)和this的区别,再来看看这个例子:(假设,我的页面中a标签包含img,并含有src属性),当我在遍历的时候,想取到$(this)下img中src的地址

      $("#desktop a ").each(function(index){

         var imgurl=$(this).find('img').attr('src');

         alert(imgurl);

        }

其中 .find(element) 是返回一个用于匹配元素的DOM元素,这样就可以取到想要的src地址了。



// this其实是一个Html 元素。
// $this 只是个变量名,加$是为说明其是个jquery对象。
// 而$(this)是个转换,将this表示的dom对象转为jquery对象,这样就可以使用jquery提供的方法操作。
 
 
( function ($){
     $.fn.hilight = function (options){
         debug( this );
 
         var defaults = {
             foreground: 'red' ,
             background: 'yellow'
         };
 
         var opts = $.extend({}, $.fn.hilight.defaults, options);
 
         return this .each( function () {
       // this其实是一个Html 元素。
       // $this 只是个变量名,加$是为说明其是个jquery对象。
       // 而$(this)是个转换,将this表示的dom对象转为jquery对象,这样就可以使用jquery提供的方法操作。
             $ this = $( this );
 
             // build element specific options
             var o = $.meta ? $.extend({}, opts, $ this .data()) : opts;
             
             // update element styles
             $ this .css({
                 backgroundColor: o.background,
                 color: o.foreground
             });
 
             var markup = $ this .html();
             // call our format function
 
             markup = $.fn.hilight.format(markup);
 
             $ this .html(markup);
         });
 
     };
 
 
     // define our format function
     $.fn.hilight.format = function (txt) {
         return '<strong>' + txt + '</strong>' ;
     };
 
 
     // 插件的defaults
     $.fn.hilight.defaults = {
         foreground: 'red' ,
         background: 'yellow'
     };
 
     function debug($obj) {
         if (window.console && window.console.log){
             window.console.log( 'hilight selection count: ' + $obj.size());
         }
     };
 
})(jQuery)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值