Jquery外掛程式開發

來源:互聯網
上載者:User

標籤:

參考:http://blog.csdn.net/salc3k/article/details/7286338

1、首先要將外掛程式程式碼封裝裹在

(function($){/*代碼從這裡開始*/})(jQuery);

代碼解釋:(function(){})(),這句代碼指的是建立一個匿名函數function(){}並立即執行, 並在參數中傳入了jQuery對象,所以在代碼中你就可以“$”使用jQuery對象,將代碼放入匿名函數中的目的:在函數中定義的變數是局部變數,不會與全域變數衝突。

2、添加外掛程式

添加外掛程式通過

$.fn.changeColor = function(){/*外掛程式作業碼從這裡開始this指當前jquery對象*/ this.css(‘background-color‘,‘red‘);}

通過這句我們就添加了一個名叫changeColor的外掛程式,這時任何jquery對象都可以使用這個外掛程式了,使用方法例如,$(‘#test‘).changeColor(),這個外掛程式實現的功能是將當前jquery對象的文本顏色改為red。

/*外掛程式代碼*/(function($){    $.fn.changeColor = function(){            this.css(‘background-color‘,‘red‘);        }})(jQuery);

可以直接包裹在javascript如下

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script><script type="text/javascript">/*外掛程式代碼*/(function($){    $.fn.changeColor = function(){            this.css(‘background-color‘,‘red‘);        }})(jQuery);</script></head><body><span id="test">jquery外掛程式開發教程</span><button onclick="$(‘#test‘).changeColor()">變顏色</button></body></html>

也可以直接加到Jquery庫裡面去如下

 

Jquery外掛程式開發

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.