简体   繁体   中英

How to create html element <li> tag inside <ul>

I have li and input inside my ul tag and I want to generate and create my own html tag in javascript. So far here is what I've got from my default html view:

<ul id="my_list" class="ks-cboxtags" style="margin-left:80px; margin-top:-20px">
  <li><input type="checkbox" id="checkboxOne"><label for="checkboxOne">valA</label></li>
  <li><input type="checkbox" id="checkboxTwo"><label for="checkboxTwo">valB</label></li>
  <li><input type="checkbox" id="checkboxThree"><label for="checkboxThree">valC</label></li>                                   
</ul>

my point of view or pseudo code is something like this:

temp_list = ["ValA","ValB","ValC"];

$.each(temp_list, function (i, item) {
  console.log(item.proc_area); //-- need dynamic html tag here to be passed inside the ul tag                    
});

You can simply append() the element ( li ) in each iteration with the current item .

Demo:

 var temp_list = ["ValA","ValB","ValC"]; $.each(temp_list, function (i, item) { $('#my_list').append($('<li>').html(`<label>${item}</label>`)); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="my_list" class="ks-cboxtags" style="margin-left:80px;"></ul>

 var template = `<input type="checkbox" id="checkbox_{{counter}}"><label for="checkbox_{{counter}}">{{label}}</label>`; var temp_list = ["ValA", "ValB", "ValC"]; $.each(temp_list, function(i, item) { var values = { counter: i, label: item }; var parsedTemplate = template.replace(/{{(\\w+)}}/g, function(_,k){ return values[k]; }); $('#my_list').append($(`<li>${parsedTemplate}</li>`)); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="my_list" class="ks-cboxtags" style="margin-left:80px;"></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