jQuery入門:數組的三種類型三種操作
眾所周知,jQuery是對JavaScript的一種高效的封裝,所以jQuery要操作的數組即是JavaScript中的數組,在JavaScript中我們使用for以及for-in進行數組的操作,而在jQuery中則使用$.map()、$.each()來操作數組:
首先是普通的數組(索引為整數的數組):
- $.map(arr,fn);
對數組中的每個元素調用fn函數逐個進行處理,fn函數將處理返回***得到的一個新的數組
- var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];
- var newarr = $.map(arr, function(item) {return item*2 });
還可以省略function的參數,這個時候this可以得到遍歷的當前元素的值
- var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];
- $.each(arr, function(key, value) { alert("key:" + key + "value:" + value); });
然后是索引為字符串的 鍵值對數組,針對這類數組,
一般采用$.each(array,fn)來操作:
- var arr = { "jim": "11", "tom": "12", "lilei": "13" };
- $.each(arr, function(key, value)
- { alert("姓名:"+key+"年齡:"+value); });
當然也可以使用無參的的function進行遍歷;
當這類數據從服務器端獲取時可以如下進行:
服務器端:
- <%@ WebHandler Language="C#" Class="Handler" %>
- using System;
- using System.Web;
- using System.Web.Script.Serialization;
- using System.Collections.Generic;
- public class Handler : IHttpHandler {
先實例化了三個person對象,然后放到一個集合中,***把這個集合序列化成字符串流到客戶端;
客戶端:
- <!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>
- <title></title>
- <script src="../myjs/jquery-1.4.2.js" type="text/javascript"></script>
- <script type ="text/javascript" >
- $.get("Handler.ashx", function(data) {
- var persons = $.parseJSON(data);
- $.each(persons, function(key, person) {
- alert("Age:"+person.Age+"Name:"+person.Name) });
- });
- </script>
- </head>
- <body>
- </body>
- </html>
客戶端通過$.parseJSON()將后臺傳遞過來的字符串轉化為js數組對象,接下來我們就使用操作普通數組的方式來操作這個得到的數組
第三種就是通過標簽選擇器獲取的jQuery對象數組,
- <!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>
- <title></title>
- <script src="../myjs/jquery-1.4.2.js" type="text/javascript"></script>
- <script type ="text/javascript" >
- $(function() {
- $("p").text("這是p標簽");
- });
- </script>
- </head>
- <body>
- <p></p>
- <p></p> <p></p> <p></p> <p></p>
- <p></p>
- </body>
- </html>
在瀏覽器中運行的效果為:
在dom加載完成后為每一個p元素動態的添加了文本,首先$("p")獲取p標簽的集合,相當于JavaScript中的document.getElementByTagName只是這里得到的是jQuery對象的數組,這樣就有了jQuery固有的隱式迭代的功能,后面的text("這是p標簽")的操作就迭代到了每一個P標簽上,我們也可以顯示的調用each函數來顯示的迭代獲得的jQuery對象數組,顯示的調用each可以看作是對$.each()的簡化調用,下面的代碼同樣可以實現上面的效果:
- <!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>
- <title></title>
- <script src="../myjs/jquery-1.4.2.js" type="text/javascript"></script>
- <script type ="text/javascript" >
- $(function() {
- $("p").each(function() {
- $(this).text("這是p標簽");
- });
- });
- </script>
- </head>
- <body>
- <p></p>
- <p></p> <p></p> <p></p> <p></p>
- <p></p>
- </body>
- </html>
原文鏈接:http://www.cnblogs.com/xieLongBao/archive/2011/01/14/1935920.html
【編輯推薦】