本文标签:jQuery JavaScript web
众所周知,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 });
alert(newarr);
还可以省略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 {
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; Person p1 = new Person { Age = "22", Name = "tom" }; Person p2 = new Person { Age = "23", Name = "jim" }; Person p3 = new Person { Age = "24", Name = "lilei" }; IList persons = new List {p1,p2,p3}; JavaScriptSerializer js = new JavaScriptSerializer(); string s= js.Serialize(persons); context.Response.Write(s); } public class Person { public string Name { get; set; } public string Age { get; set; } } public bool IsReusable { get { return false; } } }
先实例化了三个person对象,然后放到一个集合中,最后把这个集合序列化成字符串流到客户端;
客户端: - "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- "http://www.w3.org/1999/xhtml">
-
-
-
-
-
-
-
-
-
-
客户端通过$.parseJSON()将后台传递过来的字符串转化为js数组对象,接下来我们就使用操作普通数组的方式来操作这个得到的数组
第三种就是通过标签选择器获取的jQuery对象数组, - "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- "http://www.w3.org/1999/xhtml">
-
-
-
-
-
-
-
-
-
-
-
-
在浏览器中运行的效果为:
在dom加载完成后为每一个p元素动态的添加了文本,首先$("p")获取p标签的集合,相当于JavaScript中的document.getElementByTagName只是这里得到的是jQuery对象的数组,这样就有了jQuery固有的隐式迭代的功能,后面的text("这是p标签")的操作就迭代到了每一个P标签上,我们也可以显示的调用each函数来显示的迭代获得的jQuery对象数组,显示的调用each可以看作是对$.each()的简化调用,下面的代码同样可以实现上面的效果: - "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- "http://www.w3.org/1999/xhtml">
-
-
-
-
-
-
-
-
-
-
-
-
原文链接:http://www.cnblogs.com/xieLongBao/archive/2011/01/14/1935920.html
|