我无法让排序函数正常工作。我正在动态创建 a href
的列表我想在附加链接时对其进行排序。这是生成 a href 的 JQuery 代码:
var matchScoresText='<a href="#breakdownDialog" data-transition="slidefade" class="ui-btn" data-icon="arrow-r" data-iconpos="right" id="cvResults"> <h3>' + //data-rel="dialog" data-transition="pop"
response.title +
'</h3> <span id="percentageContainer"> ' + response.percentage +
'%</span></a>';
$('#resultsList').append(matchScoresText);
#resultsList
是 a href 附加到的 div 元素。添加这些后,我尝试按 <span>
的内容对列表进行排序。标签。这是由 response.percentage
填充的,这是一个数字。
orderedLinks=$('#resultsList > a').sort(sortByPercentage);
$('#resultsList').append(orderedLinks);
我无法完全正确地理解排序函数本身。目前它看起来像这样:
function sortByPercentage(a, b){
return $('#percentageContainer').text() < $('#percentageContainer').text() ? 1 : -1;
}
我怀疑这是问题所在,但我不确定如何选择 #percentageContainer
的内容.
最佳答案
在 sort
处理函数中,您需要使用与 span 相关的
元素。您还需要将值转换为 int 或 float,具体取决于所需的精度。试试这个:a
和 b
参数提供的值被迭代的 a
中的
var $orderedLinks = $('#resultsList a').sort(sortByPercentage);
$('#resultsList').append($orderedLinks);
function sortByPercentage(a, b){
return parseFloat($(a).find('span').text()) - parseFloat($(b).find('span').text());
}
关于javascript - 使用包含在其中的 span 标签的内容对 href 标签列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29073341/