如何将项目添加到无序列表< ul>使用jQuery [英] How to add items to a unordered list <ul> using jquery

查看:109
本文介绍了如何将项目添加到无序列表< ul>使用jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在json响应中,我想使用$ .each遍历它,然后将项目追加到<ul></ul>元素.

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

     }

我想添加一个

  • ,并创建一个链接到用户页面的href标记.

    I want to add a

  • , and create a href tag that links to the users page.

    推荐答案

    最有效的方法是创建一个数组并将其附加到dom一次.

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

    您可以通过丢失字符串中的所有字符串concat使它变得更好.要么多次推送到数组,要么使用+ =构建字符串,然后推送,但是对于某些人来说,读取起来会有点困难.

    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.

    还可以将所有项目包装在父元素(在本例中为ul)中,并将其附加到容器中以实现最佳性能.只需在每个字符前后插入'<ul>''</ul>',然后附加到div.

    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>

    这篇关于如何将项目添加到无序列表&lt; ul&gt;使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆