如何将新的li标签动态添加到无序列表

时间:2017-01-29 07:48:36

标签: javascript html

我想创建一个包含我的视频的列表。我尽我所能,但它不起作用。以下是我的代码。

我的代码有问题吗?

<!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>

1 个答案:

答案 0 :(得分:3)

您的代码中存在一些问题。

  1. 在循环内声明的变量用索引声明,该索引不正确并抛出错误。声明变量如 var li,var a ,这些变量将在下一次迭代中被覆盖。

  2. 您的代码中没有listItem对象,它是listItems

  3. 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>