JQuery .each()和$ .each数组问题

时间:2013-09-23 09:05:12

标签: jquery html arrays image-gallery each

我是jquery和javascript的新手很抱歉,如果这个问题看起来很愚蠢。

我尝试在几个div中加载相应文件夹的内容(图像)来制作图库。

<div id="menu">
<div class="gallery" id="div0">ok0</div>
<div class="gallery" id="div1">ok1</div>
<div class="gallery" id="div2">ok2</div>
<div class="gallery" id="div3">ok3</div>
<div class="gallery" id="div4">ok4</div>
<div class="gallery" id="div5">ok5</div>        
</div>

<script>
var $container = $("#menu div.gallery");    
  $container.each(function(){
    var $n = $(this).attr('id');
    tl = 0;

    var img = ["0001","0002","0003","0004","0005","0006","0007","0008","0009"];
    $.each(img,function (i, v) {
    $container.append('<div class="gallery_img" style="top:' + tl + 'px; left:' + tl + 'px; background-image:url(imgsmall/'+ $n +'/'+ v +'.jpg);"></div>');
      tl += 8;});           
});

$container.width(tl + 200).height(tl + 200).find("div").mouseover(
    function () {
    $(this).topZIndex();
    }
);  
</script>

每个div id对应于文件夹的名称,但由于$ container.each()函数和$ .each(),我无法找到在good div中上传好文件夹内容的方法一。这样它就会上传每个div中所有文件夹的内容。

另外如何替换此数组

  var img = ["0001","0002","0003","0004","0005","0006","0007","0008","0009"];

有什么整洁的东西?

1 个答案:

答案 0 :(得分:0)

  

这样它就会上传每个div中的所有文件

这是因为对于每个<div>,您遍历所有图像以将它们附加到DOM。

如果<div>和图片的顺序相同,您可以执行以下操作:

var img = ["0001","0002","0003","0004","0005","0006","0007","0008","0009"];
$container.each(function(index, el){
    var $n = el.attr('id');
    tl = 0;

    var currentImg = img.splice(index, 1);

    el.append('<div class="gallery_img" style="top:' + tl + 'px; left:' + tl + 'px; background-image:url(imgsmall/'+ $n +'/'+ currentImg +'.jpg);"></div>');

      tl += 8;           
});