Home > Web Front-end > JS Tutorial > body text

Jquery知识点二 jquery下对数组的操作_jquery

WBOY
Release: 2016-05-16 18:12:06
Original
799 people have browsed it

首先是普通的数组(索引为整数的数组):
$.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);

$.each(array,fn)对数组array每个元素调用fn函数进行处理,没有返回值
复制代码 代码如下:

var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];
$.each(arr, function(key, value) { alert("key:" + key + "value:" + value); });

还可以省略function的参数,这个时候this可以得到遍历的当前元素的值
复制代码 代码如下:

var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];
$.each(arr, function() { alert(this); });

然后是索引为字符串的 键值对数组,针对这类数组,
一般采用$.each(array,fn)来操作:
复制代码 代码如下:

var arr = { "jim": "11", "tom": "12", "lilei": "13" };
$.each(arr, function(key, value) { alert("姓名:"+key+"年龄:"+value); });

当然也可以使用无参的的function进行遍历;
当这类数据从服务器端获取时可以如下进行:
服务器端:
复制代码 代码如下:


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对象,然后放到一个集合中,最后把这个集合序列化成字符串流到客户端;

客户端:
复制代码 代码如下:












客户端通过$.parseJSON()将后台传递过来的字符串转化为js数组对象,接下来我们就使用操作普通数组的方式来操作这个得到的数组

第三种就是通过标签选择器获取的Jquery对象数组,
复制代码 代码如下:















在浏览器中运行的效果为:
Jquery知识点二 jquery下对数组的操作_jquery
在dom加载完成后为每一个p元素动态的添加了文本,首先$("p")获取p标签的集合,相当于Javascript中的document.getElementByTagName只是这里得到的是Jquery对象的数组,这样就有了Jquery固有的隐式迭代的功能,后面的text("这是p标签")的操作就迭代到了每一个P标签上,我们也可以显示的调用each函数来显示的迭代获得的Jquery对象数组,下面的代码同样可以实现上面的效果:
复制代码 代码如下:














Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!