jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jQuery – 按className排序DIV大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个DIV列表,像这样:

<div id="list">
    <div class="cat1-4.2"><div>4</div></div>
    <div class="cat3-3.3"><div>3</div></div>
    <div class="cat2-5.1"><div>5</div></div>
    <div class="cat3-1.5"><div>1</div></div>
    <div class="cat3-2.4"><div>2</div></div>
</div>

我想用jQuery对它们进行排序

在服务器端,我可以定义所需的订单,并在类名中包含此订单:

CATX-4.2

我想能够调用一个订单(在我的例子中,这个DIV将在第4个位置),或者第二个订单(它将在第2个位置):这解释了“4.2”

所以,如果我打电话给OrderDIV(1),我会这样:

1
2
3
4
5

如果我打电话给OrderDIV(2)我会这样:

5
4
3
2
1

(我需要添加更多订单,例如:catX-4.2.5.6.2)

非常感谢您的帮助!

解决方法

你在中途改变了要求……就像真正的客户一样.更新版本附带一些注释.只是为了确认,前面有两个“可配置”变量.

classPrefix:用于确定排序顺序的类唯一的“前缀”(在这种情况下为“cat”)
listElementSELEctor:用于获取要排序的列表的jQuery选择器.

function OrderDIV(position)
{
    var classPrefix = 'cat';
    var listElementSELEctor = '#list';

    // -- Decrement the position to make it 0 based
    position--;

    // -- Parses the "position" section from the given classes,and
    //    then the position at the specific index requested.
    var parsePosition = function(classes,pos) {
        // -- Split the "classes" into an array.
        var classList = classes.split(' ');

        // -- Determine which of the "classes" starts with the prefix we want.
        for( var i in classList )
        {
            if( classList[i].substr(0,classPrefix.length) == classPrefix )
            {
                // -- Strip out the positions section,and split it.
                var positions = classList[i].split('-')[1].split('.');

                // -- return the one position we want
                return positions[pos];
            }
        }

        // -- In the event that we don't find the class we're looking for ...
        return -1;
    }

    // -- Compares div A to div B,and returns an inDicator of the order
    var funcSort = function(a,b) {
        // -- Use "parsePosition" to determine the sortable criteria from the classes.
       var compA = parsePosition($(a).attr('class'),position);
       var compB = parsePosition($(b).attr('class'),position);
       return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
    };

    // -- SELEct the list element.
    var list = $(listElementSELEctor);

    // -- SELEct the list items,and return them as an array.
    var listitems = list.children('div').get();

    // -- Sort the array using the "funcSort".
    listitems.sort(funcSort);

    // -- Go through each of the array entries,and "append" them to the list container
    //   (this moves them to the 'BACk' of the list)
    $.each(listitems,function(idx,itm) { list.append(itm); });
}

大佬总结

以上是大佬教程为你收集整理的jQuery – 按className排序DIV全部内容,希望文章能够帮你解决jQuery – 按className排序DIV所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。