按嵌套的隐藏输入值对 <li> 元素进行排序
Sorting <li> elements by nested hidden input values
示例 DOM:
<ul class="children">
<li class="child_container" rel="1803">
<input type="hidden" name="content_child_meta[1803][sort_order]" value="2">
</li>
<li class="child_container" rel="2843">
<input type="hidden" name="content_child_meta[2843][sort_order]" value="1">
</li>
<li class="child_container" rel="3803">
<input type="hidden" name="content_child_meta[3803][sort_order]" value="3">
</li>
</ul>
尝试使用嵌套输入中的值对 <''li> 进行排序。
确实尝试了以下操作:
var child_container = jQuery("ul");
child_container.find("li.child_container").sort(function (a, b) {
return +a.find("input[name$='[sort_order]']").val() - +b.find("input[name$='[sort_order]']").val();
})
.appendTo( child_container );
还有一些其他变体,但这家伙排队没有运气......
有什么帮助吗?
您可以使用:
$(".children li").sort(sort_li).appendTo('.children');
function sort_li(a, b){
return (parseInt($(b).find('input').val(), 10)) < (parseInt($(a).find('input').val(), 10)) ? 1 : -1;
}
工作演示
因为jQuery是一种数组,所以Array.prototype.sort()
可以很好地工作;排序后,您可以将这些元素推回父元素。
总的来说,它看起来像这样:
$(".children").append(function() {
return $(this).children().sort(function(a, b) {
return $('input', a).val() - $('input', b).val();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="children">
<li class="child_container" rel="1803">
<input type="hidden" name="content_child_meta[1803][sort_order]" value="2">
</li>
<li class="child_container" rel="2843">
<input type="hidden" name="content_child_meta[2843][sort_order]" value="1">
</li>
<li class="child_container" rel="3803">
<input type="hidden" name="content_child_meta[3803][sort_order]" value="3">
</li>
</ul>
$(document).ready(function(){
$('#order').click(function(){
var sorted =$('.children').find('input:hidden').sort(function(a,b){
return parseInt(a.value)- parseInt(b.value)
});
for(var i=0;i<=sorted.length;i++){
$('.children').append($(sorted[i]).parent('li'));
}
});
});`
相关文章:
- 完全可链接的li元素
- 使用li元素的html内容更改该元素的背景
- 需要在量角器中找到使用ng中继器的li元素的数量
- 根据输入值创建li元素
- 要更改变量的高度li元素
- 为li元素添加标题
- 在不使用sort()的情况下获取HTML LI元素的副本
- 将内容从 JSON 数组附加到 li 元素
- 获取 LI 元素的偏移宽度(或等效项)
- addClass 到当前 li 元素并删除类
- 使用纯JS点击即可从li元素中获取文本和id
- Rails-使用Ajax删除li元素
- 对具有相同类级别的不同li元素进行排序
- 显示/隐藏具有不同类的li元素
- 从ul中删除li元素
- 从OL中移除LI元素
- 删除不起作用的li元素
- 从javascript生成的li a元素触发onclick
- 如何使用json对象作为li元素的id属性或使用javascript锚定标记id
- 添加和删除jquery-li元素