如何使用javascript或jQuery重新排列html元素的显示顺序?

时间:2017-07-30 19:33:13

标签: javascript jquery html5

我正在尝试根据特定div或元素所具有的特定值重新排列项目的顺序,例如,此处是以下代码段

<app-g-switch [_value]="1"> </app-g-switch>
$(document).ready(function() {
  $("button").on("click", function() {

    var spanElemenet = document.getElementsByClassName("rs");
    var stringInp = [];
    var numConv = [];
    var sorted;
    for (var counter = 0; counter < spanElemenet.length; counter++) {
      stringInp[counter] = spanElemenet[counter].innerHTML;
    }
    numConv = stringInp.map(Number);
    for (var i = 1; i < (spanElemenet.length); i++) {
      for (var j = 0; j < (spanElemenet.length) - 1; j++) {
        if (numConv[j] > numConv[j + 1]) {
          sorted = numConv[j];
          numConv[j] = numConv[j + 1];
          numConv[j + 1] = sorted;

        }
      }
    }
    //This loop is just to display output of sorted list
   for(var k = 0; k< spanElemenet.length;k++)
   {
     $("#output").append(numConv[k] + "<br>");
   }
  })
})

到目前为止,我能够从HTML中获取价值并按升序对它们进行排序,主要部分是现在根据此顺序显示容器内的所有元素以及它的div元素 < / p>

我期待的O / P会是这样的:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class="item">One : <span id="s1" class="rs">400</span></div>
  <div class="item">Two : <span id="s2" class="rs">1200</span></div>
  <div class="item">Three : <span id="s3" class="rs">5000</span></div>
  <div class="item">Four : <span id="s4" class="rs">1096</span></div>
  <div class="item">Five : <span id="s5" class="rs">99 </span></div>
</div>
<button>Re order me</button>
<div id="output">

</div>

1 个答案:

答案 0 :(得分:2)

要执行您的操作,您只需在export元素上实现自己的sort()逻辑,该元素读取并比较其子.item元素中的文本。像这样:

.rs
$("button").on("click", function() {
  $('#container .item').sort(function(a, b) {
    return parseInt($(a).find('.rs').text(), 10) - parseInt($(b).find('.rs').text(), 10);
  }).appendTo('#container');
});