javascript - 使用包含在其中的 span 标签的内容对 href 标签列表进行排序

标签 javascript jquery html sorting

我无法让排序函数正常工作。我正在动态创建 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 相关的 ab 参数提供的值被迭代的 a 中的 元素。您还需要将值转换为 int 或 float,具体取决于所需的精度。试试这个:

var $orderedLinks = $('#resultsList a').sort(sortByPercentage);
$('#resultsList').append($orderedLinks);

function sortByPercentage(a, b){
    return parseFloat($(a).find('span').text()) - parseFloat($(b).find('span').text());
}

Example fiddle

关于javascript - 使用包含在其中的 span 标签的内容对 href 标签列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29073341/

相关文章:

php - 验证此图像验证码。 Jquery PHP 和 JavaScript

javascript - 使用php转换为json

javascript - jQuery 遍历优于选择器吗?

php - JQuery 和 PHP Cookie

javascript - 生成具有特定模式的 "serial"代码

javascript - 我怎样才能让我的 anchor 链接像它下降时那样平滑地滚动回顶部?

javascript - 使用json从flickr获取图片,并将所选图片放入我的新div中

html - 版式与 HTML 标签

javascript - jQuery - 为每次点击添加越来越多的图像

javascript - 当我合并时,Magento 忽略了我的 javascript 文件