使用属性对标签排序

时间:2013-02-06 21:11:41

标签: javascript jquery

我有这个HTML

<td colspan="4" class="item"> DERBY LINE, VT 05830<br>
    <label for="" data-sort="16.26">UPS Ground $16.26</label><br>
    <label for="" data-sort="27.57">UPS 3 Day Select&reg; $27.57</label><br>
    <label for="" data-sort="33.87">UPS 2nd Day Air&reg; $33.87</label><br>
    <label for="" data-sort="72.82">UPS Next Day Air $72.82</label><br>
    <label for="" data-sort="7.99">USPS Priority $7.99</label><br>
    <label for="" data-sort="9.61">FEDEX SmartPost&reg; FedEx Delivered Via USPS $9.61</label><br>
    &nbsp;
    <input type="button" name="Button5" id="Button5" onmouseout="this.className='btn'" onmouseover="this.className='btn_over'" onclick="document.shipquote.action='shipquote.asp?action=clean';document.shipquote.submit();" value="Clear" class="btn">
</td>

我需要通过“data-sort”属性对其进行排序,现在我正在使用它 this element sorter 但是当我运行脚本时它会返回

<td colspan="4" class="item"> DERBY LINE, VT 05830<br>
    <label for="" data-sort="16.26">UPS Ground $16.26</label><br>
    <label for="" data-sort="27.57">UPS 3 Day Select&reg; $27.57</label><br>
    <label for="" data-sort="33.87">UPS 2nd Day Air&reg; $33.87</label><br> 
    <label for="" data-sort="7.99">USPS Priority $7.99</label><br>
    <label for="" data-sort="72.82">UPS Next Day Air $72.82</label><br>
    <label for="" data-sort="9.61">FEDEX SmartPost&reg; FedEx Delivered Via USPS $9.61</label><br>
    &nbsp;
    <input type="button" name="Button5" id="Button5" onmouseout="this.className='btn'" onmouseover="this.className='btn_over'" onclick="document.shipquote.action='shipquote.asp?action=clean';document.shipquote.submit();" value="Clear" class="btn">
</td>

因为你可以看到它运行但由于某种原因它只获得attr上的第一个数字。我正在使用的电话如下:

$('.item label').sortElements(function(a, b){
    return $(a).attr("data-sort") > $(b).attr("data-sort") ? 1 : -1;
});       

我做错了什么?

1 个答案:

答案 0 :(得分:5)

看起来它当前正在将每个值视为一个字符串,并按照相应的顺序对它们进行排序,1 - 9.您应该使用parseFloat()将字符串中的值转换为float以确保比较做得正确:

$('.item label').sortElements(function(a, b){
   return parseFloat($(a).attr("data-sort")) > parseFloat($(b).attr("data-sort")) ? 1 : -1;
});  

或者使用.data()方法,它会自动将数字解释为浮点数:

$('.item label').sortElements(function(a, b){
   return $(a).data("sort") > $(b).data("sort") ? 1 : -1;
});