0

jquery を使用して一連の要素のテキストを配列に抽出し、配列に要素を挿入した後に並べ替えたいと考えています。ただし、並べ替えは機能していません (配列は並べ替え後も同じ順序のままです)。どうしたの?コードの抜粋は以下のとおりです。

var sortedList = [];
$("div.resource").each(function(i, item) {
    var resource = $(this).html().toLowerCase();
    sortedList.push(resource);
})

// Add the new item 
sortedList.push(resource_name.toLowerCase());

alert("before sort");
for (var i = 0; i < sortedList.length; i++) {
    alert(sortedList[i]);
}

// Sort the list
sorted = sortedList.sort();

alert("after sort");
for (var i = 0; i < sorted.length; i++) {
    alert(sorted[i]);
}
4

2 に答える 2

2

これを試してください:

var sortedList = [];
$("div.resource").each(function(i, item) {
    var resource = $.trim($(this).text()).toLowerCase();
    sortedList.push(resource);
})
于 2012-07-23T20:35:54.153 に答える
2

In addition to the suggestions to use text() instead of html() and to trim the strings, wrap everything in the jQuery Document Ready function which will give the elements and jQuery library time to load (if you haven't already done that).

Beyond that it could be a browser issue. It works for me in chrome using both html() and text(). Though I made sure the elements only have text in them.

Also probably not a huge issue but your .each() method is missing a semi-colon.

于 2012-07-23T20:43:09.047 に答える