如何循环动态生成的id?

时间:2014-08-20 16:01:35

标签: javascript jquery

        /**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&#34; #fish1&#34;这将像#fish1,#fish2#fish3一样动态生成......实际上我希望这个函数应该为所有生成的id运行请给我一个洗脱和一个主要问题鱼正在反对这个代码我经过讨厌的PLZ可以帮助我......

3 个答案:

答案 0 :(得分:2)

添加课程&#39; fish&#39;到你的#Fishes元素。然后:

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

答案 1 :(得分:2)

如果你想继续为你的&#34; fish&#34; (#fish1,#fish2等)

请参阅此问题&#39; s answer

$("[id^=fish]")

这读取,&#34;对于id为以&#39; fish&#39; ...&#34;开头的每个元素。

答案 2 :(得分:0)

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

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();