我有一个 div 列表,我想按它们的 ID 值进行排序。问题在于 ID 的值如下:“indexNumber123”。
我想对它们进行“数字”排序,如“indexNumber1”、“indexNumber2”、“indexNumber3”,以便在显示 HTML 之前重新排序。
这个应用程序的代码库一团糟,所以我想我可以通过使用 jquery 进行 DOM 操作来完成此操作,然后就可以完成它了。
我尝试通过获取 div 数组,然后将比较函数传递给数组的排序方法来实现此目的。我以为我可以在比较方法中解析 ID 值并比较数值,但这并没有正确对它们进行排序。
function compare(a,b) {
var aId = parseInt(a.id.replace( /^\D+/g, ''));
var bId = parseInt(b.id.replace( /^\D+/g, ''));
if (aId < bId)
return -1;
if (aId > bId)
return 1;
return 0;
}
//fired on a button click
function sortNumeric() {
var arrDivs = [];
$('[id^="indexNumber"]').each(
function() {
arrDivs.push($(this)[0]);
});
var sortedDivs = arrDivs.sort(compare);
console.dir(sortedDivs);
}
最佳答案
function compare(a,b) {
var aId = parseInt(a.id.replace( /^\D+/g, ''));
var bId = parseInt(b.id.replace( /^\D+/g, ''));
return +aId - +bId
}
//fired on a button click
function sortNumeric() {
var arrDivs = $('[id^="indexNumber"]'),
sortedDivs = arrDivs.sort(compare);
console.dir(sortedDivs);
}
试试这个。您可能需要将“stringID”转换为 NumberID
关于javascript - 按 ID 值对 div 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166216/