微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jQuery中$this和$(this)的区别介绍一看就懂

<div class="jb51code">
<pre class="brush:js;">
// 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其实是<a href="https://www.jb51.cc/tag/yige/" target="_blank" class="keywords">一个</a>Html 元素。
  // $this 只是个变量名,加$是为说明其是个jquery对象。
  // 而$(this)是个转换,将this表示的dom对象转为jquery对象,这样就可以使用jquery提供的<a href="https://www.jb51.cc/tag/fangfa/" target="_blank" class="keywords">方法</a>操作。
        $this = $(this);

        // build element specific options
        var o = $.<a href="https://www.jb51.cc/tag/Meta/" target="_blank" class="keywords">Meta</a> ? $.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 '<h3>' + txt + '</h3>';
};


// <a href="https://www.jb51.cc/tag/chajian/" target="_blank" class="keywords">插件</a>的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)

原文地址:https://www.jb51.cc/jquery/53504.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐