如何使用jquery随机删除同一类的元素

How to randomly remove elements of same class using jquery

本文关键字:一类 元素 jquery 何使用 随机 删除      更新时间:2023-09-26

我有大约72个class="box"分区

这些是一些黑色的方框,覆盖了我的整个页面,我想在我的功能完成后,一个接一个地随机删除这些分区。

以下是我正在做的随机删除这些盒子,

function removeBoxes(){
    var erase;
            //var to store the length of array of divisions
    var total = $(".box").length;
    while(total > 0)
    {
              //generating a random number
        erase = Math.floor(Math.random() * total);
        $(".box").eq(erase).fadeOut(10000, function(){
            $(this).remove();
        });
        total = $(".box").length;
    }
}

稍后,我还会在两次移除之间添加一些时间延迟,但现在我只想知道如何逐个移除这些框。

一个小插件怎么样:

(function($) {
    $.fn.random = function() {
        var n = this.length;
        var r = Math.floor(n * Math.random());
        return n ? $(this[r]) : $();
    };
})(jQuery);

用法:

(function iterate() {
    $('.box').random().fadeOut(1000, function() {
        $(this).remove();
        iterate();
    });
})();

元素将一次消失一个,当不再有.box元素时,循环将自动终止。

请参阅http://jsfiddle.net/alnitak/cddhL/用于演示。

function removeBoxes(){
    var total = $(".box").length - 1;
    var randomnumber = Math.floor(Math.random()*total);
    jQuery(".box:eq('"+randomnumer+"')").fadeOut(1000, function() {
        $(this).remove();
    });
}

//这是为了每5秒删除DIV

setInterval(function(){ 
    removeBoxes();    
}, 5000);

我希望这能有所帮助:(

您都知道如何在淡出后触发某个东西,即在回调中执行,在回调中您都准备好移除框。不使用循环,而是编写一个只删除一个随机框的函数,并在回调中调用它。

示例:

function removeRandomBox() {
  var boxes = $(".box"); // don't repeatedly search for the boxes
  var total = boxes.length;
  if (length > 0) {
    var erase = Math.floor(Math.random() * total);
    boxes.eq(erase).fadeOut(10000, function(){
       $(this).remove();
       removeRandomBox();
    });
  }
}