2013-07-02 33 views
1

http://jsfiddle.net/fkling/nXkDp/js按钮上的id排序

嗨,即时尝试将此脚本连接到按钮,但它不工作。我不知道为什么。

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]);} 
}; 
+3

按钮在哪里? – mishik

+0

可能是因为您的HTML缺少按钮 – SomeShinyObject

+3

问题“如何将此代码挂接到按钮?”或者“为什么这种排序功能不适用于我的清单?”编辑:我只是看着小提琴,显然这种工作。您是否告诉我们您可以编写这样的排序函数,但是您不能执行按钮单击事件处理程序? – nnnnnn

回答

1

创建一个按钮和onload事件,它分配的onclick处理您sortID()功能:

jsFiddle Demo

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; 
} 
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()作为explained at MDN

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/