Array.prototype.sort()
を使用してDOM.Elementをソートします。JavaScript Array.prototype.sort()DOM.HTMLLIElementを呼び出すことができません
私はこのようにしてみてください:
var e = document.getElementById('test-list').children;
[].forEach.call(e,function(ee){
console.log(ee);
});
// print each child in e
[].sort.call([3,4,1],function(a,b){
console.log(a+","+b);
});
// 3,4; 4,1; [3, 4, 1]; compares every two elements
[].sort.call(e,function(a,b){
console.log(a+","+b);
});
// CAN NOT work! don't print anything.
<ol id="test-list">
<li class="lang">Scheme</li>
<li class="lang">JavaScript</li>
<li class="lang">Python</li>
<li class="lang">Ruby</li>
<li class="lang">Haskell</li>
</ol>
Array.prototype.sort()
のAPIの基本、sort()
は、より基本的なタイプよりも、通常のオブジェクトに使用することができます。
そして私は、だから私は理由HTMLLIElementsの配列内の要素がsort()
は何とかそれを考え出し、直接変更することはできないという事実を前提と
e[0].innerText = 232; // <li class="lang">232</li> ;works
e[0] = "123"; //<li class="lang">232</li> ;not work
を見つけました。だからsort()
ちょうど飛び出して戻ります。
そうですか?そして、施設が助けてsort()
が配列を扱うかどうか決定するのを助けますか?
この 'Array.prototype.slice.call(document.getElementById( 'test-list')。children)'のような配列に変換してみてください。 – destoryer
'Array.prototype.slice.call'は[HTMLCollectionを配列に変換する最も効率的な方法]から' [] .slice.call'と同じです(http://stackoverflow.com/questions/222841/most-efficient-way -to-an-htmlcollection-to-an-array)に変換します。そしてそれは本当に同じように働いた。 – d4rkb1ue
http://stackoverflow.com/questions/7059090/array-prototype-sort-call –