排序并将 li 附加到 UL ASC

sorting and appending li to ul asc

本文关键字:UL ASC li 排序      更新时间:2023-09-26

http://jsfiddle.net/Hms7Y/14/

上面的代码适用于根据"级别"插入项目,而无需使用任何复杂的排序算法,但是有一个问题,当没有现成的标记时,级别 2 仍将位于级别 1 之上。

$(document).ready(function() {
  $('button').click(function() {
    var lvl = $('select').val();
    var ref = $('li.level' + lvl).last();
    var newLi =  $('<li class="level'+ lvl + '">' + lvl + ' </li>');
    console.log(ref);
    (ref.length > 0) ? newLi.insertAfter(ref) : $("ul").append(newLi);
  });
});

我已经编辑了你的小提琴,让你按照你的期望工作:http://jsfiddle.net/Hms7Y/23/

基本上,我在每次单击时都添加了此控件:

if($("ul").children().length>0){
    $("li").each(function(){
        if(lvl <= parseInt($(this).html())){
            newLi.insertBefore($(this));
        }else{
            newLi.insertAfter($(this));
        }
    });
}else{
    $("ul").append(newLi);
}