Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
957 views
in Technique[技术] by (71.8m points)

json - How to add items to a unordered list <ul> using jquery

In my json response, I want to loop through it using $.each and then append items to a <ul></ul> element.

    $.each(data, function(i, item) {

        // item.UserID
        // item.Username

     }

I want to add a

, and create a href tag that links to the users page. See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The most efficient way is to create an array and append to the dom once.

You can make it better still by losing all the string concat from the string. Either push multiple times to the array or build the string using += and then push but it becomes a bit harder to read for some.

Also you can wrap all the items in a parent element (in this case the ul) and append that to the container for best performance. Just push the '<ul>' and '</ul>' before and after the each and append to a div.

data = [
{
  "userId": 1,
  "Username": "User_1"
},
{
  "userId": 2,
  "Username": "User_2"
}
];

var items = [];

$.each(data, function(i, item) {

  items.push('<li><a href="yourlink?id=' + item.UserID + '">' + item.Username + '</a></li>');

}); // close each()

$('#yourUl').append(items.join(''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="yourUl">
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...