现在在我的代码中,我有一个动态构建的表,然后用户将一些数据输入到表中的字段中。之后,我想向用户提供根据该字段对列表进行排序的机会。我想做的是使用 document.getElementsByClassName 获取所有值字段,然后对它们进行排序,但维护对象数据,如下所示。
var posts = document.getElementsByClassName('data');
posts.values.sort(); // I'd like to sort the array by the value of the html objects
for(i=0;i<posts.length;i++){
//modify table order
}
最佳答案
您需要先将 HTMLCollection 转换为数组,然后再排序。
var posts = document.getElementsByClassName('data');
var arr = [].slice.call(posts); // convert HTMLColleciton to Array
arr.sort();
编辑:Sort 将函数作为参数,允许您根据数组的属性进行排序
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
关于javascript - 对 document.getElementsByClassName 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30362883/