簡體   English   中英

jQuery 將子元素添加到新創建的元素

[英]jQuery Adding Child Elements to Newly Created Element

我遇到了一些 jQuery 的問題。 我正在嘗試使用 jQuery foreach 循環將 HTML 附加到新創建的元素,但它似乎不起作用。 基本上,目標是從 Javascript 數組動態生成鏈接列表。 第一步是制作列表項 (< li >),然后在新創建的 li 上附加一個錨點 ( <a href="..."> )。 但它只生成列表項而不附加錨點。

這是我目前使用的代碼:

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

想法?

似乎缺少'導致問題

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM