原文地址:http://docs.jquery.com/tutorials:getting_started_with_jquery
最好有javascript以及dom方面的知識,這對于理解其中的代碼很有幫助,不了解也不要緊,因為代碼本身就很簡潔。
這篇指南包括了 hello jquery、基本的selector、event、ajax、fx、以及一些插件。
tips:當你看到這篇文章時最好在第一時間看完,不要放到收藏夾里等待將來的某天再翻出來看,往往這一天不會到來。
其實在我之前已經有人翻譯了這篇文章,但是我覺得翻譯得有點粗糙,不易閱讀,因此又重新翻譯了一下,對我自己也又溫習了一下jquery。
ok!出發了
- setup
- hello jquery
- find me: using selectors and events //定位
- rate me: using ajax //投票
- animate me: using effects //動畫
- sort me: using the tablesorter plugin //排序
- plug me: writing your own plugins //插件
- next steps
setup(安裝)
下載地址:http://docs.jquery.com/downloading_jquery
得到jquery.js后,將其包含到目標文件就可以了,就像這樣
- $(document.ready(function() {
- // do stuff when dom is ready
- });
當dom都加載完后執行里面的語句,類似于window.onload。
那么載入完成后,我們來做些事情。
- $(document.ready(function() {
- $("a".click(function() {
- alert("hello jquery!";
- });
- });
當點擊任何一個鏈接時,都會彈出一個框,里面是什么內容,就不用我說了吧。
我們來品品這幾句話,首先是”$()”,這個可以當作一個選擇器,里面可以是tagname,比如例子中的”a”,還可以是什么,我們下面再說。
然后是一個click方法,相當于在每一個鏈接里都加了一句”onclick=…”,從這里可以看出jquery的一個很大的優點就是代碼和結構分離。
|||find me(定位)
我想很多人喜歡jquery,很大一部分是她方便的定位,也正是這一特性,使得代碼和結構分離。
jquery有兩種方法來定位。一種是css和xpath,通過傳遞一個字符串給選擇器$,比如’$(”div > ul a”)’;另一種使用了一些methods,比如find。
先來看看第一個:
- $(document.ready(function() {
- $("#orderedlist".addclass("red";
- });
注意到了$函數的參數里有一個”#”,這個表示以id來定位,所以這句話將定位到id為orderedlist的dom,然后有一個addclass方法,顧名思義,就是添加一個class,class的名字是red。
下面我們再來添加一些方法給這個元素的下級。
- $(document.ready(function() {
- $("#orderedlist > li".addclass("blue";
- });
這將選擇所有id為orderedlist的li元素,并給它們添加一個blue class。
接著,我們來點復雜的,當鼠標移到上面時addclass,移走時removeclass,但只作用于最后一個li元素。
- $(document.ready(function() {
- $("#orderedlist li:last".hover(function() {
- $(this.addclass("green";
- },function(){
- $(this.removeclass("green";
- });
- });
再來品一品這段代碼,我覺得這段代碼里最關鍵的就是這個”,”,這個逗號免去了再寫一遍$(”#orderedlist li:last”)的麻煩。this指代的是當前所選的dom。
js中的onxxxx,在jquery中都有相對應的,比如onchange,onsubmit等等。
|||有了上面的這些已經能做許多事了,再來看看上面說的第二種方法
- $(document.ready(function() {
- $("#orderedlist".find("li".each(function(i {
- $(this.append( " bam! " + i ;
- });
- });
出現了find方法,這句話的意思還是比較好理解的,定位到id為orderedlist的dom,找到所有的li元素,每一個都添加一個默認函數。
append方法是添加一些文字到所選的dom,所以這些文字會出現在dom的末尾。
如果要在提交form成功后,清空form
- $(document.ready(function() {
- // use this to reset a single form
- $("#reset".click(function() {
- $("#form".reset();
- });
- });
當點擊reset后,通過調用reset方法,id為form的表單將會被重置。
如果要使所有的表單都清空,則只需去掉form前面的”#”即可。
如果要從dom中選取一組相似的元素,可以使用filter() 和 not(),filter將只選取符合表達式的元素。而not則正相反。
- $(document.ready(function() {
- $("li".not("[ul]".css("border", "1px solid black";
- });
這段代碼的意思是選取所有的li元素(但該li不能包含ul子元素),給它們加上邊框。
css方法,前面是屬性,后面是值(這只是用法之一)。
更進一步,如果我們要選取所有包含name屬性的鏈接,則可以使用下面這段代碼。
- $(document.ready(function() {
- $("a[@name]".background("#eee";
- });
很簡單吧,通過@指定就行了,如果要指定name為jquery的鏈接,也很方便,a[@name=jquery]就ok啦。
如果只匹配部分,只需將=改為*=,比如要找到所有包含jquery的name,(匹配jquery plugin、jquery home 等等)a[@name*=jquery]
|||可以選擇parent,比如這段代碼
- $(document.ready(function(){
- $("a".hover(function(){
- $(this.parents("p".addclass("highlight";
- },function(){
- $(this.parents("p".removeclass("highlight";
- });
- });
順便說一句,$(document).ready(callback) 可以縮寫成 $(callback)
使用 ajax
這里不使用原來的例子,因為我覺得不是那么容易明白,所以用了jquery官方的例子,edit in place
url:http://docs.jquery.com/tutorials:edit_in_place_with_ajax
示范1
瀏覽者能夠在他所看的頁面的相應位置點擊編輯,而無需打開新頁面。
demo1:http://15daysofjquery.com/examples/jqueryeditinplace/divedit.php
- $(document.ready(function(){
- setclickable();
- });
當頁面載入完成后,激活setclickable函數。
- function setclickable() {
- $('#editinplace'.click(function(){ ... });
- }
這個應該就不用說了吧,設置id為editinplace的dom的click事件。
- var textarea = '<div><textarea rows="10" cols="60">' + $(this.html() + '</textarea>';
- var button = '<div><input type="button" value="save" class="savebutton" /> or <input type="button" value="cancel" class="cancelbutton"/></div></div>';
- var revert = $(this.html();
這個對應上面的省略號,也就是函數體。分別定義了3個變量,textarea是用來生成編輯框的,$(this).html指代的是原來該dom的內容。button用來生成保存和取消按鈕。revert用來相應取消事件。
然后是
- $(this.after(textarea+button.remove();
after的作用就是在目標dom的后面加上相應的內容,remove就是移去目標內容,所以這里有兩步,先是加上編輯框和按鈕,然后移去之前的內容。
||| - $('.savebutton'.click(function(){savechanges(this, false;});
- $('.cancelbutton'.click(function(){savechanges(this, revert;});
為兩個按鈕定義click事件。
- .mouseover(function() {
- $(this.addclass("editable";
- })
- .mouseout(function() {
- $(this.removeclass("editable";
- });
定義鼠標移入和移走事件。
接著定義savechanges函數
- function savechanges(obj, cancel { ... }
如果cancle是false的話,那就意味著要保存編輯后的內容
- if (!cancel {
- var t = $(obj.parent().siblings(0.val();
- // ...
- }
parent()對應的是input外面的div,siblings對應的是相鄰的dom,0指的是前面的dom,也就是
- <textarea rows="10" cols="60">' + $(this).html() + '</textarea>
接下來該來點關鍵的了
- $.post("test2.php",{content: t},function(txt){
- alert(txt;
- });
jquery的ajax方法,.post表示以post方式提交,第一個參數是目標頁面,在這里就是”test2.php”,第二個參數是提交的內容,最后是回調函數。txt是服務端傳遞過來的參數。
- else {
- var t = cancel;
- }
如果cancle不為false的話,就執行revert()方法。
- $(obj.parent().parent().after('<div id="editinplace">'+t+'</div>'.remove() ;
移走textarea和button,恢復原狀。
最后再調用setclickable方法就可以了,所有的js
- $(document.ready(function(){
- setclickable();
- });
-
- function setclickable() {
- $('#editinplace'.click(function() {
- var textarea = '<div><textarea rows="10" cols="60">'+$(this.html()+'</textarea>';
- var button = '<div><input type="button" value="save" class="savebutton" /> or <input type="button" value="cancel" class="cancelbutton" /></div></div>';
- var revert = $(this.html();
- $(this.after(textarea+button.remove();
- $('.savebutton'.click(function(){savechanges(this, false;});
- $('.cancelbutton'.click(function(){savechanges(this, revert;});
- })
- .mouseover(function() {
- $(this.addclass("editable";
- })
- .mouseout(function() {
- $(this.removeclass("editable";
- });
- };
-
- function savechanges(obj, cancel {
- if(!cancel {
- var t = $(obj.parent().siblings(0.val();
- $.post("test2.php",{
- content: t
- },function(txt){
- alert( txt;
- });
- }
- else {
- var t = cancel;
- }
- if(t=='' t='(click to add text)';
- $(obj.parent().parent().after('<div id="editinplace">'+t+'</div>'.remove();
- setclickable();
- }
|||動畫效果
使用show()和hide()方法就能完成簡單的動畫效果
- $(document.ready(function(){
- $("a".toggle(function(){
- $(".stuff".hide('slow';
- },function(){
- $(".stuff".show('fast';
- });
- });
toggle方法對應點擊事件,當點擊目標dom時,輪流執行函數。所以上面這段代碼的意思是當點擊鏈接時,class名為stuff的dom出現和隱藏的效果交替。
可以通過animate()函數來創建復雜的動畫效果。
- $(document.ready(function(){
- $("a".toggle(function(){
- $(".stuff".animate({ height: 'hide', opacity: 'hide' }, 'slow';
- },function(){
- $(".stuff".animate({ height: 'show', opacity: 'show' }, 'slow';
- });
- });
jquery有一個非常好的插件 interface plugin ,通過它可以創建更多更炫的效果,瀏覽地址:http://interface.eyecon.ro/
排序:tablesorter 插件
tablesorter 插件 可以在客戶端排序表格的數據,插件下載地址:http://motherrussia.polyester.se/jquery---escaped_anchor:cdcc6a6e460c630945c44113b9c458c7--/tablesorter/
在載入這個插件的后,可以這么調用它
- $(document.ready(function(){
- $("#large".tablesorter();
- })
點擊表頭,表格的數據就會進行相應的排序
- $(document.ready(function() {
- $("#large".tablesorter({
- // class names for striping supplied as a array.
- stripingrowclass: ['odd','even'],
- // stripe rows on tablesorter init
- striperowsonstartup: true
- });
- });
tablesorter的官方網站可以查看示例和使用方法,瀏覽地址:http://motherrussia.polyester.se/jquery---escaped_anchor:cdcc6a6e460c630945c44113b9c458c7--/tablesorter/
編寫自己的插件
只要照著下面的方法做,那么編寫一個插件也是很簡單的。
插件名稱
給插件命名,這里以”foobar”為例,創建一個jquery.[pluginname].js,比如jquery.foobar.js
添加一個客戶端方法
- jquery.fn.foobar = function() {
- // do something
- };
之后就可以這么調用了
- $(....foobar();
默認設置
- jquery.fn.foobar = function(options {
- var settings = jquery.extend({
- value: 5, name: "pete", bar: 655
- }, options;
- };
可以直接調用,也可以自己添加參數
- $("...".foobar({ value: 123, bar: 9 });
說明文檔
如果開放自己的插件,那么應該有一個說明文檔再配上實例。有了這些基本的概念之后,我們就來寫一個小插件
|||多選框插件
如果將jquery用于form,那么碰到radio和checkboxes時,可能會這么處理
- $("input[@type='checkbox']".each(function() {
- this.checked = true;
- this.checked = false; // or, to uncheck
- this.checked = !this.checked; // or, to toggle
- });
如果嫌麻煩的話,可以寫個插件來處理each
- jquery.fn.check = function() {
- return this.each(function() {
- this.checked = true;
- });
- };
現在就可以這么使用這個插件了
- $("input[@type='checkbox']".check();
當然也可以為uncheck() 和 togglecheck()寫個插件,但在這里我們作為參數選項來達到這個目的。
- jquery.fn.check = function(mode {
- // if mode is undefined, use 'on' as default
- var mode = mode || 'on';
-
- return this.each(function() {
- switch(mode {
- case 'on':
- this.checked = true;
- break;
- case 'off':
- this.checked = false;
- break;
- case 'toggle':
- this.checked = !this.checked;
- break;
- }
- });
- };
這樣默認就是on,調用的話,就可以這樣
- $("input[@type='checkbox']".check();
- $("input[@type='checkbox']".check('on';
- $("input[@type='checkbox']".check('off';
- $("input[@type='checkbox']".check('toggle';
可選設置
- jquery.fn.rateme = function(options {
- // instead of selecting a static container with
- // $("#rating"), we now use the jquery context
- var container = this;
-
- var settings = jquery.extend({
- url: "rate.php"
- // put more defaults here
- }, options;
-
- // ... rest of the code ...
-
- // if possible, return "this" to not break the chain
- return this;
- });
調用的時候
- $(....rateme({ url: "test.php" });
下一步
如果想更加熟悉或者開發js項目,可以考慮一下firefox的firebug插件