寫 jQuery 時,this、$this、$(this) 這幾個寫法經常讓新手犯糊塗。其實只要理清它們的本質,就一目了然了。下面的代碼片段配上註釋,把三者的關係講得很清楚:
// 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) 歸納一下:this 指向的是原生 HTML 元素;$this 只是一個約定俗成的變量名,習慣上加 $ 前綴來表明它是一個 jQuery 對象;而 $(this) 則是一次「包裝」動作,把 this 所代表的 DOM 對象轉換成 jQuery 對象,這樣就能使用 jQuery 提供的各項方法了。理解這一點,是寫好 jQuery 插件與事件處理的基礎。