我有一个动态创建的 ul 和 li 我必须按照特定的任意顺序进行组织。
这是生成的 HTML 的示例:
<ul id="myUl">
<li id="myId_15" class="myId_class">A list item</li>
<li id="myId_264" class="myId_class">Another list item</li>
<li id="myId_573" class="myId_class">Yet another list item</li>
</ul>
这是我到目前为止为这部分管理的 jQuery:
var slicedCompIds = ["15","573","264"];
$.each(slicedCompIds, function(i){
$('#myUl').append($('#myUl li').attr('id', 'myId_' + slicedCompIds[i]));
})
目标是使用“slicedCompIds”数组中的顺序按 id 重新组织或排序列表。它不会按数字升序排列,很可能是随机的。
目前我的代码正在生成这个:
<ul id="myUl">
<li id="myId_264" class="myId_class">A list item</li>
<li id="myId_264" class="myId_class">Another list item</li>
<li id="myId_264" class="myId_class">Yet another list item</li>
</ul>
它保持相同的顺序,但只是将 id 替换为“slicedCompIds”数组中的最后一个 id。
我真的很难理解我必须申请这部分的逻辑,因此我要征求意见。谁能指出我正确的方向?
谢谢!
最佳答案
您的代码存在问题是因为在 append()
调用中您获取了所有 li
元素然后更改了 id
属性在将它们追加回原来的位置之前,第一个的。
要修改逻辑以执行您需要的操作,您需要根据数组中的值通过 id
单独选择每个元素,然后 append()
仅此元素。试试这个:
var slicedCompIds = ["15","573","264"];
slicedCompIds.forEach(function(value, i){
$('#myUl').append($('#myId_' + value));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myUl">
<li id="myId_15" class="myId_class">A list item</li>
<li id="myId_264" class="myId_class">Another list item</li>
<li id="myId_573" class="myId_class">Yet another list item</li>
</ul>
关于javascript - 基于数组按 ids 组织列表 - jQuery/JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43873092/