jQuery将子元素添加到新创建的元素中

时间:2019-12-04 04:46:47

标签: javascript jquery html css

我遇到了一些jQuery问题。我正在尝试使用jQuery foreach循环将HTML附加到新创建的元素上,但似乎无法正常工作。基本上,目标是从Javascript数组动态生成链接列表。第一步是制作列表项(<li>,然后将锚点(<a href="...">)附加到新创建的li。但是它仅生成列表项,而不附加锚点。

这是我当前正在使用的代码:

    // Define the Array
    pages = ["page1.php", "page2.php", "page3.php"]
    // Loop through each page
    pages.forEach(function(page) {
        // Build the first li and give it a unique id
        $("#sidelinks").append($("<li class='nav-item' id='navlink-"+pages.indexOf(page)+"'></li>"));
        // Store the newly create li as a var
        var newLink = $("#navlink-" + pages.indexOf(page));
        // Append the anchor to the newly create li
        newLink.html("<a href='" + page + "' class='nav-link text-dark font-italic>Introduction</a>");
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="sidelinks">
</ul>

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

似乎缺少'会导致问题

class='nav-link text-dark font-italic>Introduction</a>");
                                     ^ (') missing here

// Define the Array
pages = ["page1.php", "page2.php", "page3.php"]
// Loop through each page
pages.forEach(function(page) {
  // Build the first li and give it a unique id
  $("#sidelinks").append($("<li class='nav-item' id='navlink-" + pages.indexOf(page) + "'></li>"));
  // Store the newly create li as a var
  var newLink = $("#navlink-" + pages.indexOf(page));
  // Append the anchor to the newly create li
  newLink.html("<a href='" + page + "' class='nav-link text-dark font-italic'>Introduction</a>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="sidelinks">
</ul>