【问题标题】:how to loop the dynamically generated id? [duplicate]如何循环动态生成的id? [复制]
【发布时间】:2014-10-14 02:06:08
【问题描述】:
        /**Script**/ 
      function AnimateFish() {
        var Fish3 = $("#fish1").not(".HoverFish"),
            theContainer = $("#container"),
            maxLeft = theContainer.width() - Fish3.width() - 50,
            maxTop = theContainer.height() - Fish3.height(),
            leftPos = Math.floor(Math.random() * maxLeft),
            topPos = Math.floor(Math.random() * maxTop) + 100,
            imgRight = "Assets/fish-glow3-right.gif",
            imgLeft = "Assets/fish-glow3.gif";


        if (Fish3.position().left <= leftPos) {
            $(this).css("background-image", 'url("' + imgRight + '")');
        } else {
            $(this).css("background-image", 'url("' + imgLeft + '")');
        }

        Fish3.animate({
            "left": leftPos,
            "top": topPos
        }, 1800, AnimateFish);
    }
 AnimateFish();

您好,id "#fish1" 将像 #fish1、#fish2 #fish3 一样动态生成...实际上我希望应该为所有生成的 id 运行此函数,请给我解决方案和一个主要问题鱼我尝试了很多此代码是否会反转,请 PPL 帮助我...

【问题讨论】:

  • 使用选择器来执行此操作。 stackoverflow.com/questions/5002966/…
  • 而且这个网站通常不会很好地回应“给我解决方案”。除了我认为的问题之外,您的问题还很完善。欢迎加入社区
  • 他没有说“给我解决方案”,他只是想要解决方案。

标签: javascript jquery


【解决方案1】:

免责声明:这是未经测试的,但它应该可以帮助您获得良好的模式

function AnimateFish() 
{
    var aFish      = $('[id^="fish"]:not(.HoverFish)'); // get the fish that aren't hovering
    var oContainer = $("#container");

    aFish.each(function(nIndex, oFish)
    {
        var nMaxLeft   = oContainer.width()  - oFish.width() - 50;
        var nMaxTop    = oContainer.height() - oFish.height();
        var nLeftPos   = Math.floor(Math.random() * nMaxLeft);
        var nTopPos    = Math.floor(Math.random() * nMaxTop) + 100;
        var sImgRight  = "Assets/fish-glow3-right.gif";
        var sImgLeft   = "Assets/fish-glow3.gif";

        if (oFish.position().left <= nLeftPos)
            $(this).css("background-image", 'url("' + sImgRight + '")');
        else 
            $(this).css("background-image", 'url("' + sImgLeft + '")');

        oFish.animate({
            "left": nLeftPos,
            "top" : nTopPos
        }, 1800, AnimateFish);
    }
}
AnimateFish();

【讨论】:

  • 感谢我能够选择所有 id,如果我有不止一条鱼,则背景图像无法正常工作“鱼正在反转”,如果条件有些问题可以给出解决方案?我试过lotttt :(
  • 老实说,我不确定。我刚刚清理了代码以完成您最初的问题。可能尝试调整 if 以使条件反转或者问题出在动画中?深入研究它可能是我能告诉你的唯一解决方案
  • 如果它只反转我可以这样做,但它随机反转并直线前进:(
  • 嗯.. 我不确定。对其进行调试并检查可能导致该行为的任何相关值,或发布另一个问题。
【解决方案2】:

如果您想继续为您的“鱼”(#fish1、#fish2 等)使用 ids

查看这个问题的answer

$("[id^=fish]")

这读作“对于每个 id 以 'fish' 开头的元素...”

【讨论】:

    【解决方案3】:

    将“鱼”类添加到您的#Fishes 元素。那么:

    $(".fish").each(function () {
      //do your stuff here, $(this) representing your #Fish element
    });
    

    【讨论】:

    • 可能不需要循环。您可以将 $([id^=fish]) 用于某些事情
    • 你说得对,催化剂的答案更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    相关资源
    最近更新 更多