gpt4 book ai didi

javascript - js 按按钮上的 id 排序

转载 作者:行者123 更新时间:2023-11-28 02:08:40 26 4
gpt4 key购买 nike

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

最佳答案

创建一个按钮并加载,将其 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;
}

关于javascript - js 按按钮上的 id 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17426023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com