1.$(selector).each(function(index,element))
2.$.each(dataresource,function(index,element))
接下来就对这两个函数做深入的探讨:
1.$(selector).each(function(index,element))
作用:在dom处理上面用的较多 (html 元素、节点)
示例:
遍历数组。html部分文档
- Coffee
- Soda
- Milk
js遍历函数:
function traversalDOM(){
KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲each_id li").ea…(this).text())
});
}
输出结果:
2.$.each(dataresource,function(index,element))
作用:在数据处理上用的比较多
示例:
遍历JSON 对象。此处没有html代码,只有js代码,如下:
function traversalData(){
var jsonResourceList =
‘[{“id”:“1”,“tagName”:“apple”},
{“id”:“2”,“tagName”:“orange”},
{“id”:“3”,“tagName”:“banana”},
{“id”:“4”,“tagName”:“watermelon”}]’;
//JSON.parse() 把json字符串转化为一个对象
//遍历JSON 数据
if(jsonResourceList.length >0){
$.each(JSON.parse(jsonResourceList),function(index,obj) {
alert(obj.tagName);
});
}
输出结果:
3.最终结论:
在遍历DOM时(如数组),通常用
(
s
e
l
e
c
t
o
r
)
.
e
a
c
h
(
f
u
n
c
t
i
o
n
(
i
n
d
e
x
,
e
l
e
m
e
n
t
)
)
函
数
;
在
遍
历
数
据
时
(
如
J
S
O
N
对
象
)
,
通
常
用
(selector).each(function(index,element))函数; 在遍历数据时(如JSON 对象),通常用
(selector).each(function(index,element))函数;在遍历数据时(如JSON对象),通常用.each(dataresource,function(index,element))函数。
转自:https://blog.csdn.net/weixin_41796631/article/details/82313086