简体   繁体   中英

dynamic list sorting without using sort array

I was thinking of some sort algorithm to perform dynamic array sorting list, but this http://jsfiddle.net/Hms7Y/1/ seem able to solve my problem with cleaner code. But there's still few steps left to be done.

$(document).ready(function() {
  $('button').click(function() {
    var lvl = $('select').val();
    var ref = $('li.level' + lvl).last();
    $('<li class="level" '+ lvl + '>' + lvl + ' </li>').insertAfter(ref);
  });
});

what if initially I don't have any HTML markup, what is in my head now is use 3 if statement to check whether it's the 1st li when the user insert a li. is there any other better ways?

try this jsFiddle

$(document).ready(function() {
  $('button').click(function() {
    var lvl = $('select').val();
    var ref = $('li.level' + lvl).last();
    var newLi =  $('<li class="level'+ lvl + '">' + lvl + ' </li>');

    (ref.length > 0) ? newLi.insertAfter(ref) : $("ul").append(newLi);
  });
});

Or like this jsFiddle

(ref.length > 0) ? ref.after(newLi) : $("ul").append(newLi);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM