1

我有这个 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>

我需要它通过“数据排序”属性对其进行排序,现在我正在使用 这个元素排序器 但是当我运行脚本时它返回这个

<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;
});       

我究竟做错了什么?

4

1 回答 1

5

看起来它当前将每个值视为一个字符串并按各自的顺序对它们进行排序,1 - 9。您应该使用parseFloat()将值从字符串转换为浮点数,以确保正确完成比较:

$('.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;
});  
于 2013-02-06T21:14:32.750 回答