运行一次功能(在while循环中)

时间:2013-10-18 08:17:13

标签: javascript php jquery animation

尝试使用动画在我的while循环中运行我的函数,我移动正方形,我只希望它运行一次。不要让它工作。如果我使用setInterval,它只会动画多次。而我现在如何拥有它根本没有动画。这就是它现在的样子。欣赏一些提示。谢谢!

编辑 - 根据计数ID,将方块设置为不同的位置。

<?php
...
$count = 0;
while($rows = mysql_fetch_array($data)){ //many rows
$count = $count + 1
    $id= $rows['id']; //different id's for each row


?>
<script>
    var ID = '<?php echo $id; ?>';
            var count = '<?php echo $count; ?>';      
</script>

<div id="squares" style="height:50px; width:50px; position:relative; background:black;" >

<script>
    document.getElementById('squares').id = ID; //make div id "squares" to ID

//So here the it doesn't work.
function(){
    if(count == 1){
    $('#' + ID).animate({left: (700), top: (300)}, 2000);
    $('#' + ID).animate({left: (300), top: (500)}, 2000);
    }
    if(count == 2){
    $('#' + ID).animate({left: (100), top: (400)}, 2000);
    $('#' + ID).animate({left: (100), top: (800)}, 2000);
    }
}

</script>
<?php
}
?>

2 个答案:

答案 0 :(得分:0)

我可以看到的第一件事是,在PHP while循环中,您正在编写一堆JS脚本,每个脚本都处理单个元素的动画。您应该将其更改为单个JS脚本,以激活您的所有元素:

<?php
...    
while($rows = mysql_fetch_array($data)){ //many rows
    $id= $rows['id']; //different id's for each row
    $left = $rows['left']; // <---- replace this with your logic for determining top and left
    $top = $rows['top'];
?>

<div id="<?php echo $id; ?>" class="square" style="height:50px; width:50px; position:relative; background:black;" data-animateLeft="<?php echo $left; ?>" data-animateTop="<?php echo $top; ?>">

<?php
}
?>

<script>
$('.square').each(function(){
   $this = $(this);
   $this.animate({left: +$this.data('animateLeft'), top: +$this.data('animateTop')}, 2000);
});
</script>

答案 1 :(得分:0)

<html>
<head>
<script>

    $(document).ready(function () {
        // NOTE: I suspect what you want to do is run one animation after the other,
        // you need a callback function for that.
        $('.toBeAnimated1').animate({ left: (700), top: (300) }, 2000, function() {
            $('.toBeAnimated1').animate({ left: (300), top: (500) }, 2000);
        });
        $('.toBeAnimated2').animate({ left: (100), top: (400) }, 2000, function() {
            $('.toBeAnimated2').animate({ left: (100), top: (800) }, 2000);
        });
    });

</script>
</head>
<body>
<?php
...
$count = 0;
while($rows = mysql_fetch_array($data)){ //many rows
$count = $count + 1
    $id= $rows['id']; //different id's for each row
    ?>
    <div id="<? echo $id; ?>" class="toBeAnimated<? echo $count; ?>" style="height:50px; width:50px; position:relative; background:black;" >
<?
}
?>
</body>
</html>