[jQuery]自訂plugin(extention method)

  • 655
  • 0

摘要:[jQuery]自訂plugin(extention method)

javascript部分:

(function ($) {
	$.fn.ChangeLink = function (options) {
		//jquery官方網站建議:自訂plugin的時候,
		//強烈建議至少加入一個以上的參數
		//比較不容易被其他程式設計師複寫掉
		//利用$.extend字眼,設定預設參數value
		var settings = $.extend({
			//預設值
			targetColor: "Green",
			yesOrNoAddText: "Yes"
		}, options);
		//呼叫者在使用這個plugin的時候,可能會抓到多個dom元件
		//所以才要用each
		this.each(function () {
			var link = $(this);
			link.css("color", settings.targetColor);//改變顏色
			if (settings.yesOrNoAddText == "Yes")
			{
				link.append(" (" + link.attr("href") + ")");
			}                    
		});
		return this;

	};

}(jQuery));

//不帶入參數的使用plugin方法
function CallMyPluginWithoutParam() {            
	$("a[id*=test]").ChangeLink();
}
//帶入參數的使用plugin方法
function CallMyPluginWithParam() {
	$("a[id*=test]").ChangeLink({
		targetColor: "Red"
		, yesOrNoAddText: "No"
	});            
}

html部分:

<a href="page.html" id="test">Foo</a>
<br />
<a href="page1.html" id="test1">Foo1</a>
<br />
<input type="button" onclick="CallMyPluginWithoutParam()" value="CallMyPluginWithoutParam" />
<br />
<input type="button" onclick="CallMyPluginWithParam()" value="CallMyPluginWithParam" />
<br />

結果:

原本的樣子:

重新載入網頁後,按下CallMyPluginWithoutParam按鈕:

重新載入網頁後,按下CallMyPluginWithParam按鈕:

 

參考資料:

官方網站的How to Create a Basic Plugin

http://learn.jquery.com/plugins/basic-plugin-creation/