jQuery, random div order

前端 未结 3 2116
别跟我提以往
别跟我提以往 2021-02-04 08:57

I have this jQuery and HTML http://jsfiddle.net/UgX3u/30/

    
3条回答
  •  自闭症患者
    2021-02-04 09:29

    Try this:

    http://jsfiddle.net/UgX3u/33/

    $("div.container div").sort(function(){
        return Math.random()*10 > 5 ? 1 : -1;
    }).each(function(){
        var $t = $(this),
            color = $t.attr("class");
        $t.css({backgroundColor: color}).appendTo( $t.parent() );
    });
    

    .sort is applied to jQuery like this:

    $.fn.sort = [].sort
    

    Since it doesn't perform like other jQuery methods, it isn't documented. That does mean it is subject to change, however I doubt it will ever change. To avoid using the undocumented method, you could do it like this:

    http://jsfiddle.net/UgX3u/37/

    var collection = $("div.container div").get();
    collection.sort(function() {
        return Math.random()*10 > 5 ? 1 : -1;
    });
    $.each(collection,function(i,el) {
        var color = this.className,
            $el = $(el);
        $el.css({backgroundColor: color}).appendTo( $el.parent() );
    });
    

提交回复
热议问题