简体   繁体   中英

jQuery Adding Child Elements to Newly Created Element

I am running into a problem with some jQuery. I am attempting to append HTML to a newly create element using a jQuery foreach loop, but it seems to not be working. Basically, the goal is to generate list of links dynamically from a Javascript array. Step one is to make the list item (< li >) and then append an anchor ( <a href="..."> ) to the newly created li. But it is only generating the list items and not appending the anchor.

Here is the code I am currently using:

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

Thoughts?

Seems missing ' causes the problem

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>

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