javascript - 在列表中的特定点插入新的 html 元素

标签 javascript jquery list

我有这个例子: 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);
  }
}

http://codepen.io/Alchemyistic/pen/NrNKLZ

最佳答案

您可以使用 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/

相关文章:

javascript - MaterializeCSS 模态标题

javascript - 如何获取AngularJS Controller 中输入字段的值

javascript - 如何在原生 javascript 中实现 $ ("<div class=' wrapper'><span>Some text</span></div>")?

parsing - ERLANG - 将列表拆分为子列表

python - 更改字典中的列表会更改所有列表

javascript - 当 JavaScript 函数的名称作为字符串传递到函数中时,如何执行该函数?

javascript - 如何重命名从Reducer.mean 获得的平均值?

javascript - 我从头开始创建 html 解析器的想法可行吗?

JQuery 插件 SimpleModal 不断重新打开动态加载的 iframe

python - 为什么 string.split ('\n' ) 在输出列表中添加一个额外的元素?