同时添加div和排序

时间:2016-08-14 11:47:10

标签: javascript jquery

我想将div添加到其他人,并根据data-sort值进行排序。

示例:

<div id="divbox">
    <div class="somediv" data-sort="0.10">some content</div>
    <div class="somediv" data-sort="0.05">some content</div>
</div>

如何将另一个div添加到值为divbox的{​​{1}},我应该放在两个div之间,我该怎么做。

2 个答案:

答案 0 :(得分:1)

使用 append() 将新的html内容附加到元素。如需订购,请使用 sort() 方法,并使用 appendTo() 方法将其反映到新订单的dom追加中。

&#13;
&#13;
// get the parent div
$('#divbox')
  // append new div to it
  .append('<div class="somediv" data-sort="0.07">some content</div>')
  // get all children divs
  .children()
  // sort the object collection based on data-sort value
  .sort(function(a, b) {
    // get difference for sorting based on number
    return $(b).data('sort') - $(a).data('sort');
    // append back to parent for updating order
  }).appendTo('#divbox');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divbox">
  <div class="somediv" data-sort="0.10">some content</div>
  <div class="somediv" data-sort="0.05">some content</div>
</div>
&#13;
&#13;
&#13;

或者你可以迭代子节点并根据属性值的比较插入div。

&#13;
&#13;
// create jQuery object of append content
var $ele = $('<div class="somediv" data-sort="0.07">some content</div>');
// get sort value of it
var dataVal = +$ele.data('sort');

// iterate over existing divs
$('#divbox .somediv').each(function(i) {
  // get sort value of current element
  var thisVal = +$(this).data('sort');
  // if sort value is greter than the first div then append the element before it
  if (i == 0 && dataVal > thisVal) {
    // append before first element
    $ele.insertBefore(this);
    // break the for loop 
    return false;
    // if the element is last or satisfies the codition for insertion
  } else if ($(this).next().length == 0 || (datVal <= thisVal && thisVal > +$(this).next().data('sort'))) {
    // insert the eleemnt 
    $ele.insertAfter(this);
    // break the loop
    return false;
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divbox">
  <div class="somediv" data-sort="0.10">some content</div>
  <div class="somediv" data-sort="0.05">some content</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用纯JS,您可以执行以下操作;

var myDiv = document.createElement("div"),
  divList = divbox.querySelectorAll(".somediv"),
     frag = document.createDocumentFragment();
myDiv.className = "somediv";
myDiv.dataset.sort = "0.07";
myDiv.textContent = "new text here 07";

divbox.appendChild([...divList].concat(myDiv)
                               .sort((a,b) => +a.dataset.sort - +b.dataset.sort)
                               .reduce((df,div) => (df.appendChild(div),df),frag));
<div id="divbox">
    <div class="somediv" data-sort="0.10">some content 10</div>
    <div class="somediv" data-sort="0.05">some content 05</div>
</div>