将 jquery 变量重置为不存在的最低可能值

Resetting jquery varible to lowest possible value that doesn't exist

本文关键字:不存在 变量 jquery      更新时间:2023-09-26

此脚本生成带有云图像的div,这些云图像以随机的高度和间隔从左向右飞行。它通常有效,但它会无限增加div "id"。我不知道如何重置安全的计数器,永远不会同时存在两个相同的"id"。

function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
function cloud(type,time,nr){
    $("#sky").append("<div id='"cloudFL"+nr+"'" class='"cloud"+type+"'" ></div>");
        setTimeout(function() { 
            $("#cloudFL"+nr).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
                left:'100%',
                },time,'linear',function(){$(this).remove();
                });
        }, Math.floor(Math.random() * t1));
}; 
function wave(){
    var tx = 0;
    setInterval(function(){
        cloud(1,t1,nr);
        nr++;
        var n = $( "div.cloud1" ).length;
        $( "span" ).text( "There are " + n +" n and "+ tx +" tx")
        if(tx < n){tx = n}
        else(tx = 1)
        },500); 
};
wave()};
cloudgenerator()

在底部,有一条指令检查div 的数量是否开始下降,并在 span 中显示这些值以进行调试。

快速简便的解决方案
您可以在 JQuery 中循环访问 id,从最小的数字开始,直到找到产生 0 结果的 JQuery 选择器......

var newid = 0;
var i = 1;
while(newid == 0) {
    if( $('#cloudFL' + i).length == 0 ) { newid = i; }
    else { i++; }
}

JSFIDDLE 演示




替代解决方案(可扩展)
鉴于您可能同时在屏幕上显示许多云,您可以尝试这种替代方法。此方法创建一个"已用 id"数组,然后 wave 函数在为云函数创建新 id 之前检查是否有任何"已用 id"可用。在屏幕上出现许多云的情况下,这将比"快速修复解决方案"更有效地运行。

function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
var spentids = [];
function cloud(type,time,id){
    $("body").append('<div id="' + id + '" class="cloud' + type + '" >' + id + '</div>');
        setTimeout(function() { 
            $('#'+id).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
                left:'100%',
                },time,'linear',function(){
                    spentids.push( $(this).attr('id') );
                    $(this).remove();
                });
        }, Math.floor(Math.random() * t1));
}; 
function wave(){
    setInterval(function(){
        if(spentids.length == 0) {
            cloud(1,t1,"cloudFL" + nr);
            nr++;
        } else {
            spentids = spentids.sort();
            cloud(1,t1,spentids.shift());                
        }
        },500); 
};
wave()};
cloudgenerator()

JSFIDDLE 演示 - 替代

为什么不获取时间戳并将其添加到您的 id 中?

如果你不需要 ids,我会坚持@hon2a,只需将样式添加到类中并删除 id。

还有另一种解决方案:

您可以检查是否使用了 ID xyz。像这样,例如

  var cloudCount = jQuery('.cloud20000').length + jQuery('.cloud50000').length + 10;
  for(var i = 0; i <= cloudCount; i++) {
    if(jQuery('#cloudFL' + i).length <= 0) {
      nr = i;
      return false;
    }
  }
  cloud(1,t1,nr);