用jQuery和js遍歷JSON文件

在vue中,遍歷只要用v-for就可以輕松的達(dá)到生成列表的效果

如果他非要用jQuery或Js呢,直接上代碼

html 就一句

<body>
  <ol class="d1"></ol>
</body>

json

[{
  "id": 1,
  "title": "天使中的魔鬼",
  "artist": "田馥甄",
  "file": "url1-1",
  "cover": "url1-2",
}, {
  "id": 2,
  "title": "風(fēng)繼續(xù)吹",
  "artist": "張國榮",
  "file": "url2-1",
  "cover": "url2-1",
}, {
  "id": 3,
  "title": "戀戀風(fēng)塵",
  "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實(shí)現(xiàn)一下

中間注釋掉的是如果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>

否則會報(bào)錯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)
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容