Jquery 遍历加拼json对象 || 获取非固有属性时应用getAttribute()直接写属性名

获取div(id=editAllRole)下class为needRoleParameter的所有对象,并输出值

$.each($("div#editAllRole .needRoleParameter"), function (i, item) {

  console.log(item.value);

  });


-------------拼json对象--------------

var json =new Array;
for (var i = RoleName.length - 1; i >= 0; i--) {
var singJson={RoleName:RoleName[i].value,RoleParameter:RoleParameter[i].value};
json.push(singJson);

}

用JSON.stringify()将对象转化为字符串

-------------------------------获取非固有属性---------------------------------------------------

注意上面的RoleName[i].value,如果获取的元素固有属性里没有value 
可尝试getAttribute("属性名"),比如下面我自定义的属性,但注意,getAttribute()方法不能通过document对象调用,这与我们此前介绍过的其他方法不同。我们只能通过一个元素节点对象调用它。

var singJson={RoleName:td_checkbox[i].getAttribute("RoleName"),ResourceGroupName:td_checkbox[i].getAttribute("GroupName")};

---------------------多种用法介绍---------------------

1. $.each方法


对于遍历一个数组,用$.each()来处理,贼爽。例如:

$.each([{“name”:”limeng”,”email”:”xfjylimeng”},{“name”:”hehe”,”email”:”xfjylimeng”},function(i,n)
{
alert(“索引:”+i,”对应值为:”+n.name);
});

参数i为遍历索引值,n为当前的遍历对象.


一些例子:

var arr1 = [ “one”, “two”, “three”, “four”, “five” ];
$.each(arr1, function(){
alert(this);
});
输出:one   two  three  four   five

-----------------------------------------------------
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
alert(item[0]);
});
输出:1   4   7

-------------------------------------------------------------

var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
输出:1   2  3  4  5


相似的$().each或其他方法也可点击查看这篇文章

发布了53 篇原创文章 · 获赞 32 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/niuniuyaobuyao/article/details/79220685