duan35557593 2015-01-21 08:40
浏览 113

在for循环和值更改时添加换行符或类似内容 - jQuery

I have a db table with users and I am creating a hierarchy system.

Currently the top users (with a 1 hierarchy) are shown, and then when clicked I gather all the related users via ajax and display below.

These users have 4 or 5 tiers for their hierarchy. 1 being the highest level.

I want to be able to make a new line of users each time the hierarchy changes.

I query the db and fetch all the users with an order by of the hierarchy number, I then put them into an array, return with JSON and loop through in jQuery:

for(var i=0; i<data.userArray.length; i++){
  var user = data.userArray[i];
  $appendedItems.append(SHOW ALL USERS HERE);
}

Lets say the array is:

hierarchy => 2, 
hierarchy => 2, 
hierarchy => 2,
hierarchy => 3, 
hierarchy => 3, 
hierarchy => 4,

Each time the hierarchy changes, I would like to show a line break or something just to put the users on a new line to denote a lower level.

Thanks.

  • 写回答

1条回答 默认 最新

  • douhuan1648 2015-01-21 09:03
    关注

    how I'd do it, obviously your case will be different but you can get the idea:

    markup:

    <ul id="#users">
        <li data-user-id="3">david</li>
        <li data-user-id="4">frank</li>
    </ul>
    

    jQuery:

    $('#users').on('click', 'li:not(.exploded)', function() {
        var $user = $(this).addClass('exploded'),
            userId = $user.data('userId'),
            url = '/getUsersChildres?user=' + userId;
    
        $.getJSON(url).then(function(data) {
            $('<ul>', {
                html: $.map(data.userArray, function(i, user) {
                    return $('<li>', {
                        text: user.name,
                        data: {
                            'userId': user.id
                        }
                    });
                })
            }).appendTo($user);
        }, function() {
            $user.removeClass('exploded');
        });
    
        return false;
    });
    

    should end up with:

    <ul id="#users">
        <li data-user-id="3" class="exploded">david
            <ul>
                <li data-user-id="13">jack</li>
                <li data-user-id="14">paul</li>
            </ul>
        </li>
        <li data-user-id="4">frank</li>
    </ul>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法