js常用循环
使用 parentNode、nextSibling、previousSibling、firstChild 和 lastChild 属性可以遍历文档树中任意类型节点,包括空字符(文本节点)。HTML 5 新添加 5 个属性专门访问元素节点。
- childElementCount:返回子元素的个数,不包括文本节点和注释。
- firstElementChild:返回第一个子元素。
- lastElementChild:返回最后一个子元素。
- previousElementSibling:返回前一个相邻兄弟元素。
- nextElementSibling:返回后一个相邻兄弟元素
1.遍历数组:
1.1:
1.2:
1.3:
2.遍历对象:
3.数据的渲染(分为拼接和创造)
var arr1 = [1,2,3,4,5,6] var aa = '' for(var key in arr1){ // 拼接 aa=aa+'<div>'+arr1[key] + '</div>' } console.log(aa) document.getElementById('b').innerHTML = aa var arr1 = [1,2,3,4,5,6] for(var key in arr1){ // 创造 var b1 = document.createElement('div') b1.innerHTML = arr1[key] document.getElementById('b').appendChild(b1) } var reobj = [ {"content":"充值卡","time":"17-09-08"}, {"content":"小米手环","time":"17-03-12"}, {"content":"IPTV","time":"18-01-02"} ] var str = '' for(var key in reobj){ // 拼接 str += '<div class="l1">' str += '<div class="p1">'+reobj[key].content+'</div>' str += '<div class="p2">'+reobj[key].time+'</div>' str+='</div>'; } document.getElementById("b").innerHTML=str; var reobj = [ {"content":"充值卡","time":"17-09-08"}, {"content":"小米手环","time":"17-03-12"}, {"content":"IPTV","time":"18-01-02"} ] for(var key in reobj){ // 创造 var b1 = document.createElement('div') var b2 = document.createElement('div') b1.innerHTML = reobj[key].content b2.innerHTML = reobj[key].time document.getElementById('b').appendChild(b1) document.getElementById('b').appendChild(b2) } var xx = [ { "id": 6,"creatorId": 4,"categories": ["11"],"description": "1+1=2", "createTime": "2020-02-23 20:27:09", "personal": false, "type": "SINGLE_CHOICE", "question": "1+1=?|||2|||11|||100|||5", "answer": "0", "prompt": "22222", "analysis": "11111111", "score": 2, "time": 2, "exams": null, "status": "NORMAL" } ] var xy = xx[0] for(var key in xy){ //创造 var b1 = document.createElement('div') b1.innerHTML = key + xy[key] document.getElementById('b').appendChild(b1) }
本文来自博客园,作者:封兴旺,转载请注明原文链接:https://www.cnblogs.com/fxw1/p/14784518.html