使用javascript更改div的顺序

时间:2015-07-27 08:57:00

标签: javascript jquery html dom reverse

我有类似的东西:

public ClassName  getLastProcessedTupleSourceDest(Long ID,
        String srcIp, String destIp) {
    String [] param = {"ID","SRC_IP","DST_IP"};
    Object [] values = {Id,"'"+srcIp+"'","'"+destIp+"'"};
    List<ClassName> tuplesByPFChek = (List<ClassName>) (hibernateTemplate
            .findByNamedQueryAndNamedParam("findTuplesWithSrcDstforCheck",param, values));
    if(!tuplesByPFChek.isEmpty() && tuplesByPFChek.get(0)!=null)
        return tuplesByPFChek.get(0);

    log.info("ali: returning null = tuplesByPFChek.isEmpty():"+tuplesByPFChek.isEmpty());
    return null;        
}   

我希望在某些情况下它会像那样,在某些情况下它会 极端逆转:

<div>

   <div id = "a"/>
   <div id = "b"/>
   <div id = "c"/>
   <div id = "d"/>
   <div id = "e"/>
   <div id = "f"/>

</div>

我在javascript中寻找一些解决方案, 任何人都有任何想法。

3 个答案:

答案 0 :(得分:2)

要对jQuery元素进行排序,您只需使用sort()方法:

$('#container div').sort(function(a, b) {
    return a.id < b.id ? -1 : 1;
}).appendTo('#container');

Example fiddle

要将订单更改为升序,请反转三元组中的-11

return a.id < b.id ? 1 : -1;

答案 1 :(得分:0)

您可以使用jQuery对元素进行排序。使用isReverse来反转排序。

function sort(arr, isReverse){
  
  arr.sort(function(a, b){
    if(a.id > b.id) return  isReverse ? -1 : 1;
    if(a.id < b.id) return isReverse ? 1 : -1;
    return 0;
  });
  return arr;
}
var parent = $("#container");
var arr = sort(parent.children(), true);
arr.detach().appendTo(parent)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="container">

   <div id = "a">a</div>
   <div id = "b">b</div>
   <div id = "c">c</div>
   <div id = "d">d</div>
   <div id = "e">e</div>
   <div id = "f">f</div>

</div>

答案 2 :(得分:0)

这是一种方法: HTML

<div id="content"></div>

JS:

var divs = new Array("a","b","c","d","e","f");

var content = document.getElementById("content");
// Original
for(var i = 0; i < divs.length; i++){
    var div = document.createElement("div");
    div.appendChild(document.createTextNode(divs[i]));
    div.setAttribute("id", divs[i]);
    content.appendChild(div);
}

// Reverse
divs.reverse();
for(var i = 0; i < divs.length; i++){
    var div = document.createElement("div");
    div.appendChild(document.createTextNode(divs[i]));
    div.setAttribute("id", divs[i]);
    content.appendChild(div);
}

https://jsfiddle.net/bigneo/jb20ad8m/