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 回答
0

您可以将事件处理程序分配给按钮,如下所示:

document.getElementById('sortButtonIdHere').addEventListener('click', function() {    
    // your code here    
}, false);

演示:http: //jsfiddle.net/nXkDp/31/

如果您担心支持 IE8 及更早版本,您可以使用:

document.getElementById('sortButtonIdHere').onclick = function() {    
    // your code here    
};

或者,您可以添加一个测试是否.addEventListener()已定义,如果不使用attachEvent(),如MDN 中所述

于 2013-07-02T12:54:34.853 回答
0

试试这个 :

HTML:

<div id="list">
    <div id="categorie5.1-4">4</div>
    <div id="categorie5.1-3">3</div>
    <div id="categorie5.1-5">5</div>
    <div id="categorie5.1-1">1</div>
    <div id="categorie5.1-2">2</div>
</div>
<input type="button" onclick="keyMe()" value="hook">

Javascript:

function keyMe(){
    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]);
    }
}

我希望它会帮助你

这是链接:jsfiddle.net/dp6Vr/

于 2013-07-02T12:56:06.223 回答