0

I'm trying to generate random div widths for each database result that's output.

The code works when it's outside the loop, but every div is the same 'random' width.

  • load page and all divs are 200px
  • refresh page and all divs are 150px
  • refresh page and all divs are 250px ...etc.

The trouble being, I need each individual div to be a random width, not all the same random width... for that reason I've added my javascript inside the loop in order to get a new 'random' width each time a database value is output.

And of course, it's not working!

<?php 
            $result = mysql_query("SELECT * from tbl_status ORDER BY tbl_status.date desc");

            while($row = mysql_fetch_array($result))
                    {
                        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
                        <script>
                        $(document).ready(function(){
                            var x = Math.floor((Math.random()*150)+150);
                            $('.statusCont').width(x+'px');
                        });
                        </script>

                        echo'
                    <div class="statusCont">
                        <div class="statusUsr">Tom Adams - Newcastle</div>
                        <div class="statusTxt"><p>' . $row['status'] . '</p></div>
                    </div><!-- ends .statusCont -->
                    ';}
            ?>
4

1 回答 1

0

所有 div 具有相同随机宽度的原因是因为 jquery 类选择器$('.statusCont')将返回该类的所有元素。因此,当您的循环打印出最后一个选择器时,它适用于所有先前加载的元素。

无需在 phpwhile循环中包含 javascript,您只需在头部编写一个脚本,该脚本将在页面加载后影响页面

$(document).ready(function () {
    $('.statusCont').each(function () {
        var x = Math.floor((Math.random() * 150) + 150);
        $(this).width(x);
      });
 );
于 2013-10-03T19:18:01.767 回答