我有这个例子: CODEPEN
如何制作它以便例如如果新的随机数是20,它会在24之后但在19之前添加?
是否有优雅的"这样做的方法还是我必须选择所有li
元素,遍历它们,并在第一个具有较低data-num的元素前面添加?
感谢。
//编辑:
结束这样做是因为我不想清空整个div并重新填充它,我认为这是最简单的方法:
$('ul > li').each(function(i){
if($(this).data('num') < newNum){
$(this).before(template);
return false; //stop .each
}
if(i == $('ul > li').length - 1){
$(this).after(template);
}
}
答案 0 :(得分:1)
您可以使用while循环执行此类操作。
$('button').on('click', function() {
var newNum = parseInt(Math.random() * (30 - 1) + 1);
var template = '<li data-num="' + newNum + '">' + newNum + '</li>';
// flag for while loop
var found = false,
// get first eleemnt from list
$ele = $('ul li[data-num]').first(),
last = false;
// iterate loop upto found element or last element
while (!found) {
// check num is greater that current item
if (newNum > +$ele.text()) {
// then set found is true
found = true;
// check there is element next to it
} else if ($ele.next().length) {
// update element variable with sibling next to current element
$ele = $ele.next();
// check content is greater than elemnt and update flag
if (newNum > +$ele.text())
found = true;
// if reached last element set flag to true, and last to true
} else {
found = true;
last = true;
}
}
// insert the element after the current element if `last` is true
if (last)
$ele.after(template);
// else insert before the element
else
$ele.before(template);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-num="24">24</li>
<li data-num="19">19</li>
<li data-num="11">11</li>
<li data-num="3">3</li>
</ul>
<button>+1</button>
答案 1 :(得分:0)
我不知道优雅。但是,这应该是一个起点:
$('button').on('click',function(){
var values = [];
$('ul').children().each(function (i, e) {
// get all the values and put them into an array
values.push(parseInt($(e).attr('data-num'), 10));
});
var newNum=parseInt(Math.random() * (30 - 1) + 1);
// push this new number into the array
values.push(newNum);
// sort all the values desc.
values.sort(function(a, b) {return -(a-b);});
// clear out the ul
$('ul').empty();
// repopulate with li
$.each(values, function (i,e) {
var template='<li data-num="'+e+'">'+e+'</li>';
//
$('ul').append(template);
})
});
对我来说,这是非常可读的(所以你可以说优雅)。这很容易理解,即使你在6个月的时间内回顾它。主要是因为自我记录代码,如.each()
.empty()
.sort()
。
这也是很少有状态的。因此,使用此代码可以减少错误(标志和其他状态引入的错误)。
答案 2 :(得分:0)
我认为这就是你想要的
$('button').on('click',function(){
var newNum=parseInt(Math.random() * (30 - 1) + 1);
var template='<li data-num="'+newNum+'">'+newNum+'</li>';
// check if number is 20 then append the template after list containing 2
if(newNum==20){
console.log(template);
$("li[data-num='24']").after().append(template);
}
else{
$('ul').append(template);
}
});