对 HTML 列表进行排序,然后对目标元素进行排序

Order an HTML list and then target elements

本文关键字:排序 目标 元素 然后 HTML 列表      更新时间:2023-09-26

我正在研究一个对HTML列表进行排序的函数。我在StackOverflow上找到了以下代码(谢谢!!),我做了一些调整。我的目标是对列表进行排序,然后在排序后显示未显示的(!(":visible")) lis 元素。该功能完美运行,无需显示未显示元素的特定部分。

function sortList(ul){ 
var new_ul = ul.cloneNode(false);
// Add all lis to an array
var lis = []; 
for(var i = ul.childNodes.length; i--;){
if(ul.childNodes[i].nodeName === 'LI')
lis.push(ul.childNodes[i]); 
} 
// Sort the lis in descending order
lis.sort(function(a, b){
return parseInt(b.getElementsByClassName(variable)[0].innerHTML , 10) - parseInt(a. getElementsByClassName(variable)[0].innerHTML , 10); 
});
if (order == 'asc') {lis.reverse();}
// Add them into the ul in order 
for(var i = 0; i < lis.length; i++) {
//THIS IS THE PART that makes the function not working anymore
    if (!lis[i].is(":visible")) {
        lis[i].fadeToggle("slow","linear");
    }
//END OF THE PART
    new_ul.appendChild(lis[i]);
}
ul.parentNode.replaceChild(new_ul, ul); 
}

我像这样调用函数: sortList(document.getElementsByClassName('list')[0],'date','asc');

我的 HTML 看起来像这样:

<ul class="list">
    <li> <span class="date">1</span></li>
    <li> <span class="date">2</span></li>
    <li style="display:none;"> <span class="date">3</span></li>
    <li style="display:none;" > <span class="date">4</span></li>
</ul>

谢谢你的帮助!

如果你打算使用jQuery作为切换函数,你需要把它包含在你的页面中

另外,您的sortList函数没有向下传递其他参数,因此,我将其更改为此

function sortList(ul, variable, order) { // <-- pass the parameters here
    var new_ul = ul.cloneNode(false);
    // Add all lis to an array
    var lis = [];
    for (var i = ul.childNodes.length; i--;) {
        if (ul.childNodes[i].nodeName === 'LI') lis.push(ul.childNodes[i]);
    }
    // Sort the lis in descending order
    lis.sort(function (a, b) {
        return parseInt(b.getElementsByClassName(variable)[0].innerHTML, 10) - parseInt(a.getElementsByClassName(variable)[0].innerHTML, 10);
    });
    if (order == 'asc') {
        lis.reverse();
    }
    // Add them into the ul in order 
    for (var i = 0; i < lis.length; i++) {
        //THIS IS THE PART that makes the function not working anymore
        /* using jQuery notation for the jQuery function calls */
        if (!$(lis[i]).is(":visible")) {  // <-- here
            $(lis[i]).fadeToggle("slow", "linear"); // <-- and here
        }
        //END OF THE PART
        new_ul.appendChild(lis[i]);
    }
    ul.parentNode.replaceChild(new_ul, ul);
}

演示 JS 小提琴

最后,如果你使用的是jQuery,你可以用一个简单的$('.className')替换你所有的getElementsByClassName(..),因为它基本上是相同的(即这是jQuery语法来完成相同的选择)