有点奇怪的要求。我有大约 300 个图像 URL 和 27 个div。每个div都有一个id="img1",其中1是一个介于 1 和(你猜对了)27 之间的数字,以及一个class="imageblock"(用于一般样式)。
在这些divs 中的每一个中,我想插入一个<img src="http://foo.bar/img.jpg" width="640">,其中 URL 是从大约 300 个随机列表中选择的,并随机插入其中一个divs 中。27 中的每一个都div应该从 300 个选项中选择自己的图像。
此外,这些图像应该循环。每隔 5 秒,我希望将页面上的一个随机图像 URL 替换为另一个随机图像 URL。
这是我试图在一点帮助下拼凑起来的(可怕的)代码,但我对 javascript 毫无用处,无法完成这项工作:
<script type="text/javascript">     
    $('document').ready(function() {        
                    var divs = $('div');
                        $("div").each(function() {
                          $(this).html("<img src='http://foo.bar/img1.jpg'alt='"+$(this).attr("id")+"'/>");         
                        });  
                        var imageChanger = setInterval(function() {switchImage()}, 500);
                        function switchImage() {
                         var new_image_url = [ 'http://foo.bar/anotherimg.jpg', 'http://bar.foo/image.jpg', 'http://foo.bar/imgremote.jpg'];
                            var random_div = Math.floor(Math.random() * $('div').length);
                            var random_img = Math.floor(Math.random() * $(new_image_url.length);
                          $("div:nth-child("+random_div+")").html('<img src="('+random_img+')" width="640">)');            
                        }
    });
    </script>
请注意,远程图像不遵循任何常见模式,从而使我的random_img变量无法正常工作。
任何帮助,将不胜感激。