標籤:cti end false each pre span 使用 鏈式 logs
1 (function ($) { 2 $.fn.extend({ 3 "highLight": function (options) { 4 //檢測使用者傳進來的參數是否合法 5 if (!isValid(options)) 6 return this; 7 var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆蓋外掛程式預設參數 8 return this.each(function () { //這裡的this 就是 jQuery對象。這裡return 為了支援鏈式調用 9 //遍曆所有的要高亮的dom,當調用 highLight()外掛程式的是一個集合的時候。10 var $this = $(this); //擷取當前dom 的 jQuery對象,這裡的this是當前迴圈的dom11 //根據參數來設定 dom的樣式12 $this.css({13 backgroundColor: opts.background,14 color: opts.foreground15 });16 //格式化高亮文本17 var markup = $this.html();18 markup = $.fn.highLight.format(markup);19 $this.html(markup);20 });21 22 }23 });24 25 26 //預設參數27 var defaluts = {28 foreground: ‘red‘,29 background: ‘yellow‘30 };31 //公用的格式化 方法. 預設是加粗,使用者可以通過覆蓋該方法達到不同的格式化效果。32 $.fn.highLight.format = function (str) {33 return "<strong>" + str + "</strong>";34 }35 //私人方法,檢測參數是否合法36 function isValid(options) {37 return !options || (options && typeof options === "object") ? true : false;38 }39 })(window.jQuery);
jquery外掛程式開發的demo