简体   繁体   中英

How to dynamically add new li tags to an unordered list

I want to create a list that will contain my videos. I tried my best but it is not working. Below is my code.

Is there any problem in my code?

 <!DOCTYPE html> <html lang="en"> <head> </head> <body> <button onclick="generateList();">Click on me</button> <script> function generateList() { var listItems = [{ filename: "Besabriyaan", path: "videos/Besabriyaan.mp4" }, { filename: "Parwah nahin", path: "videos/Parwah nahin.mp4" }, { filename: "Laila main laila", path: "videos/Laila main laila.mp4" }, { filename: "Kaabil trailer", path: "videos/Kaabil trailer.mp4" }]; var list = document.createElement("ul"); list.setAttribute("id", "song lists"); document.body.appendChild(list); for (i = 0; i < listItems.length; i++) { var li[i] = document.createElement("li"); var a[i] = document.createElement("a"); a[i].setAttribute("id", listItems.length + 1); a[i].setAttribute("href", listItems[i].path); var filename[i] = document.createTextNode(listItem[i].filename); a[i].appendChild(filename[i]); li[i].appendChild(a[i]); list.appendChild(li[i]); } }; </script> </body> </html> 

There are few issues in you code.

  1. Variables declared inside loop are declared with a index which is not correct and throwing error. Declare you variable like var li, var a , these variables will be overwritten in the next iterations.

  2. There is no listItem object in your code it is listItems

 function generateList() { var listItems = [{ filename: "Besabriyaan", path: "videos/Besabriyaan.mp4" }, { filename: "Parwah nahin", path: "videos/Parwah nahin.mp4" }, { filename: "Laila main laila", path: "videos/Laila main laila.mp4" }, { filename: "Kaabil trailer", path: "videos/Kaabil trailer.mp4" }]; var list = document.createElement("ul"); list.setAttribute("id", "song lists"); document.body.appendChild(list); var li, a, filename; for (var i = 0; i < listItems.length; i++) { li = document.createElement("li"); a = document.createElement("a"); a.setAttribute("id", "movie_" +i); a.setAttribute("href", listItems[i].path); filename = document.createTextNode(listItems[i].filename); a.appendChild(filename); li.appendChild(a); list.appendChild(li); } }; 
 <button onclick="generateList();">Click on me</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM