我需要根据票价值对下面的div元素进行排序。我需要根据key:value对进行排序,看起来像[{key:"1",value=""},{..},{..}]
。
以下代码段是我的HTML代码
<div class="panel data" key="1" fare="800"></div>
<div class="panel data" key="2" fare="300"></div>
<div class="panel data" key="3" fare="500"></div>
以下结构是我想要的输出方式。
[
{key:"2",value:"300"},
{key:"3",value:"500"},
{key:"1",value:"800"}
]
此外,我需要按照上述结构重新排序div。
请指导我如何实现这一目标。
答案 0 :(得分:0)
document.querySelector( "#sortByFare" ).addEventListener( "click", function(){
var panels = document.querySelectorAll( ".panel.data" );
[].slice.call( panels ).sort( function(a,b){
var aFare = a.getAttribute( "fare" );
var bFare = b.getAttribute( "fare" );
if ( aFare < bFare )
{
a.parentNode.insertBefore( a, b );
}
else
{
a.parentNode.insertBefore( b, a );
}
return aFare - bFare;
});
});
<div class="panel data" key="1" fare="800">800
</div>
<div class="panel data" key="2" fare="300">300
</div>
<div class="panel data" key="3" fare="500">500
</div>
<input type="button" value="Sort By Fare" id="sortByFare"/>
如果将排序逻辑重构为
,则可以进一步推广
document.querySelector( "#sortByFare" ).addEventListener( "click", function(){
var panels = document.querySelectorAll( ".panel.data" );
sortDomElements( panels, "fare" );
});
document.querySelector( "#sortByKey" ).addEventListener( "click", function(){
var panels = document.querySelectorAll( ".panel.data" );
sortDomElements( panels, "key" );
});
function sortDomElements( nodeList, attributeName )
{
[].slice.call( nodeList ).sort( function(a,b){
var aFare = a.getAttribute( attributeName );
var bFare = b.getAttribute( attributeName );
if ( aFare < bFare )
{
a.parentNode.insertBefore( a, b );
}
else
{
a.parentNode.insertBefore( b, a );
}
return aFare - bFare;
});
}
<div class="panel data" key="1" fare="800">800
</div>
<div class="panel data" key="2" fare="300">300
</div>
<div class="panel data" key="3" fare="500">500
</div>
<input type="button" value="Sort By Fare" id="sortByFare"/>
<input type="button" value="Sort By Key" id="sortByKey"/>
答案 1 :(得分:0)
我假设你在父元素中有它们 您可以选择所有子元素并循环比较值并构建重写字符串。
var parentEl= document.getElelemtById('parentID')
for (var j = 0; j < parentEl.childNodes.length; j++) {
var key = parentEl.childNodes[j].getAttribute('key');
var fare = parentEl.childNodes[j].getAttribute('fare');
// compare the fare here
// also build your new child div strings here
}
// finally output the new child string
parentEl.innerHTML= yourNewChildString;
没有对此进行过测试,但它应该能满足您的需求。
答案 2 :(得分:0)
<div id="list">
<div class="listing-item" data-fare="800">800</div>
<div class="listing-item" data-fare="300">300</div>
<div class="listing-item" data-fare="500">500</div>
</div>
var divList = $(".listing-item");
divList.sort(function(a, b){ return $(a).data("fare")-$(b).data("fare")});
$("#list").html(divList);