在vue中,遍历只要用v-for就可以轻松的达到生成列表的效果
如果他非要用jQuery或Js呢,直接上代码
html 就一句
<body>
<ol class="d1"></ol>
</body>
json
[{
"id": 1,
"title": "天使中的魔鬼",
"artist": "田馥甄",
"file": "url1-1",
"cover": "url1-2",
}, {
"id": 2,
"title": "风继续吹",
"artist": "张国荣",
"file": "url2-1",
"cover": "url2-1",
}, {
"id": 3,
"title": "恋恋风尘",
"artist": "老狼",
"file": "url3-1",
"cover": "url3-1",
}, {
"id": 4,
"title": "我要你",
"artist": "任素汐",
"file": "url4-1",
"cover": "url4-2",
}, {
"id": 5,
"title": "成都",
"artist": "赵雷",
"file": "url5-1",
"cover": "url5-2",
}, {
"id": 6,
"title": "sound of silence",
"artist": "Simon & Garfunkel",
"file": "url6-1",
"cover": "url6-1",
}]
然后来jQuery实现一下
中间注释掉的是如果json文件里含有对象嵌套的解决方法
let a = 上边的json
$.each(a, (key, value) => {
/* if (typeof (value) === 'object') {
$.each(value, (keyi, valuei) => {
console.log(valuei)
})
} else {
console.log(key);
console.log(value);
} */
$('.d1').append(`<li class=list${value.id}>${value.title}</li>`);
})
再来一段js的
这里有个坑,不能像jQuery一样在appendChild里写<li class=list${value.id}>${value.title}</li>
否则会报错Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
for (let key in a) {
let b = document.createElement('li')
b.innerHTML = `${a[key].title}`
document.getElementsByClassName('d1')[0].appendChild(b)
}
网友评论