我有这个例子: 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);
}
}
最佳答案
您可以使用 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>
关于javascript - 在列表中的特定点插入新的 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37746653/