>  기사  >  웹 프론트엔드  >  jQuery에서 $this와 $(this)의 차이점 소개(한 눈에 알 수 있음)_jquery

jQuery에서 $this와 $(this)의 차이점 소개(한 눈에 알 수 있음)_jquery

WBOY
WBOY원래의
2016-05-16 15:51:291305검색
// 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)
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.