单页上的多个图像库

时间:2015-03-05 12:09:08

标签: jquery

根据下面的代码,您可以帮助我在我的页面上使用多个图库。如果页面上只有一个库,它工作正常,在其他情况下,我必须复制代码两次,并为元素提供不同的ID。我相信有更好的解决方案。

提前致谢。

HTML

<div class="img">
    <div class="image">
        <img src="images/1.png">
        <img src="images/2.png">
        <img src="images/3.png">
    </div>
    <div class="thumbnail">
        <img src="images/1_tb.png">
        <img src="images/2_tb.png">
        <img src="images/3_tb.png">
    </div>
</div>
<div class="img">
    <div class="image">
        <img src="images/1.png">
        <img src="images/2.png">
        <img src="images/3.png">
    </div>
    <div class="thumbnail">
        <img src="images/1_tb.png">
        <img src="images/2_tb.png">
        <img src="images/3_tb.png">
    </div>
</div>

JQuery的

$(function(){
$(".image img:eq(0)").nextAll().hide();
$(".thumbnail img").click(function(e){
        var $this = $(this),
        index = $this.index();
    $(".image img").eq(index).show().siblings().hide();
});
});

2 个答案:

答案 0 :(得分:0)

按照目前的情况,按类名选择将找到DOM中的所有符合条件的元素。因此,您的画廊并不是彼此独立的。

您需要一种机制来约束每个特定图库的选择。

您的代码可以重构为jQuery插件......

//jQuery plugin
$.fn.myGallery = function() {
    this.each(function(i, gallery) {
        $(".image img:eq(0)", gallery).nextAll().hide();
        $(".thumbnail img", gallery).click(function(e) {
            $(".image img", gallery).eq($(this).index()).show().siblings().hide();
        });
    });
}

...并在class == "img"

的所有容器上调用
$(".img").myGallery();

就个人而言,我会更改类名&#34; img&#34;到&#34;画廊&#34;并使用以下命令调用插件:

$(".gallery").myGallery();

答案 1 :(得分:0)

我们的想法是分别处理图库,仅在图库中更改某些内容,例如使用.closest()查找图库主要包装:

Fiddle

JS:

$(function()
{
    $(".image").each(function()
    {
        $(this).find('img:not(:first)').hide();
    });

    $(".thumbnail img").on("click", function()
    {
        var $this = $(this);
        var index = $this.index();
        var gallery = $this.closest('.img');
        gallery.find(".image img").eq(index).show().siblings().hide();
    });
});
相关问题