循环的JavaScript排序问题 [英] JavaScript sorting issue with looping
问题描述
我不确定我的问题在这里.我有以下对表"(不是实际的HTML表)进行排序的排序过程:
I'm not entirely sure what my issue is here. I have the following sorting procedure that sorts a "table" (Not an actual HTML table):
function sortByName(tableBody) {
var projectList = [];
for (var i = 0; i < tableBody.length; i++) {
projectList.push(tableBody[i]);
}
console.log("about to enter");
//console.log(tableRows);
for(var i = 0; i < tableBody.length; i++){
var currentRow = tableBody[i];
if(currentRow.innerText !== null){
currentRow.style.display ="none";
}
}
projectList.sort(function(a,b){
var nameA = a.innerText.toUpperCase(); // ignore upper and lowercase
var nameB = b.innerText.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
console.log(projectList);
for(var q = 0; q < projectList.length; q++){
redisplayProjects(q, projectList);
}
}
function redisplayProjects(index, projectList){
console.log(projectList);
projectList[index].style.display = 'block';
}
显示在控制台上的projectList实际上是在控制台中排序的,但是在切换样式时.显示回阻止"行的顺序与预排序的顺序相同.我是否缺少任何人都可以帮助的东西?
Displaying to the console, the projectList is in fact sorted in the console but upon toggling the style.display back to 'block' the rows appear in the same order as they were pre-sorted. Am I missing something that anyone can help with?
推荐答案
假定 sortByName 函数参数tableBody
期望某个表的DOM Row集合,请使用-.
Assuming that the sortByName function-argument tableBody
is expecting a DOM Row collection of a certain table, - use this.:
function sortByName( tableBody ) {
var i = 0, projectList = [].slice.call(tableBody).
sort( function( a, b ){
var A = a.innerText.toUpperCase(), B = b.innerText.toUpperCase();
return A < B ? -1 : A > B ? 1 : 0;
}), wrapper = tableBody[0].parentElement;
while( projectList[i] )wrapper.appendChild( projectList[i++] );
}
我还假设使用即时排序功能,您无需切换元素的显示样式属性,因为它们将立即按其各自的排序顺序放置!
I'm also assuming that with this, instant sort function you will not need to switch the display style property of elements, as they will be placed in their respective sort order, instantly!
致谢.
p.s .:仍然不确定 tableBody 到底是什么,因此取决于此信息的更新,所提供的功能可能会或可能不需要进一步调整.
p.s.: still not sure what tableBody really is, therefore depending on the update to this info, the function given, might, or might not need further tweaking.
这篇关于循环的JavaScript排序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!