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]);}
};
答案 0 :(得分:1)
创建一个按钮并上传,将其onclick
处理程序分配给您的sortID()
函数:
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;
}
答案 1 :(得分: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。
答案 2 :(得分: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 /