动态填充最后一个UL中的LI内部

时间:2019-06-20 21:48:49

标签: jquery

我想创建类似这样的东西,但是要动态:

        <ul class="list-group list-group-flush">
            <li class="list-group-item list-group-item-light">
                <div class="row">
                    <label for="label1" class="col-sm-10 col-form-label col-form-label-sm">Label 1</label>
                    <div class="col-sm-2">
                        <input type="text" class="form-control form-control-sm" id="label1" placeholder="Label1" value="50">
                    </div>
                </div>
            </li>
            <li class="list-group-item list-group-item-light">
                <div class="row">
                    <label for="label2" class="col-sm-10 col-form-label col-form-label-sm">Label 2</label>
                    <div class="col-sm-2">
                        <input type="text" class="form-control form-control-sm" id="label1" placeholder="Label2" value="3">
                    </div>
                </div>
            </li>
            <li class="list-group-item list-group-item-light">
                <div class="row">
                    <label for="label3" class="col-sm-10 col-form-label col-form-label-sm">Label 3</label>
                    <div class="col-sm-2">
                        <input type="text" class="form-control form-control-sm" id="label1" placeholder="Label3" value="17">
                    </div>
                </div>
            </li>
        </ul>

li项的数量取决于它从数据库中获取了多少行。

我尝试过这样的事情:

rows.forEach(function(obj) {
  $('#custom-fields').append('<li class="list-group-item list-group-item-light"><div class="row"><label for="'+obj.id+'" class="col-sm-10 col-form-label col-form-label-sm">'+obj.label+'</label><div class="col-sm-2"><input type="text" class="form-control form-control-sm" id="'+obj.id+'" placeholder="'+obj.placeholder+'" value="50"></div></div></li>');
});

...但是我不知道如何将ul包裹起来。问题还在于页面上有很多ul,所以我不能简单地使用类似$('#custom-fields ul').append('...

的东西

有什么提示吗?

1 个答案:

答案 0 :(得分:0)

您可以制作并附加到新的ul,然后将其附加到页面。

var $newUL = $('<ul>');

rows.forEach(function(obj) {
  $newUL.append('<li class="list-group-item list-group-item-light"><div class="row"><label for="'+obj.id+'" class="col-sm-10 col-form-label col-form-label-sm">'+obj.label+'</label><div class="col-sm-2"><input type="text" class="form-control form-control-sm" id="'+obj.id+'" placeholder="'+obj.placeholder+'" value="50"></div></div></li>');
});

$('#custom-fields').append($newUL);