1

http://jsfiddle.net/fkling/nXkDp/

こんにちは、このスクリプトをボタンに接続しようとしていますが、うまくいきません。理由がわかりません。

var sortID = function()
{
var toSort = document.getElementById('list').children;
toSort = Array.prototype.slice.call(toSort, 0);

toSort.sort(function(a, b) {
    var aord = +a.id.split('-')[1];
    var bord = +b.id.split('-')[1];
    // two elements never have the same ID hence this is sufficient:
    return (aord > bord) ? 1 : -1;
});

var parent = document.getElementById('list');
parent.innerHTML = "";

for(var i = 0, l = toSort.length; i < l; i++) {
    parent.appendChild(toSort[i]);}
};
4

3 に答える 3

1

ボタンを作成してオンロードし、そのonclickハンドラーをsortID()関数に割り当てます。

jsFiddle デモ

HTML:

<input type="button" id="mybutton" value="Sort" />

Javascript:

var sortID = function () {

    var toSort = document.getElementById('list').children;
    toSort = Array.prototype.slice.call(toSort, 0);

    toSort.sort(function (a, b) {
        var aord = +a.id.split('-')[1];
        var bord = +b.id.split('-')[1];
        // two elements never have the same ID hence this is sufficient:
        return (aord > bord) ? 1 : -1;
    });

    var parent = document.getElementById('list');
    parent.innerHTML = "";

    for (var i = 0, l = toSort.length; i < l; i++) {
        parent.appendChild(toSort[i]);
    }

};

window.onload = function(){
    document.getElementById("mybutton").onclick = sortID;
}
于 2013-07-02T12:53:02.307 に答える