如何为库中显示的图像指定一个按钮 - jQuery

时间:2014-12-03 22:03:17

标签: jquery html css image gallery

我使用this漂亮的代码作为简单的滑块:

http://codepen.io/GCW/pen/ByovxG

我添加了一些导航按钮,但我不知道如何调用按钮ID引用的所选图像ID。

<button id="firstbutt">First Gallery</button>
<button id="secondtbutt">Second Gallery</button>
<button id="thirdbutt">Third Gallery</button>
<button id="fourthbutt">Fourth Gallery</button>

<img id="image1" .../>
<img id="image2" .../>
<img id="image3" .../>
<img id="image4" .../>

我对jQuery不太好,代码有很多变量,但我想我应该得到我想要显示的图像的#位置。似乎存储了一个数组。

slidePos = new Array(slides.length);

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,一个解决方案就是为每个按钮/图像对添加一个类。

所以它看起来像这样:

<button id="firstbutt" class="first">First Gallery</button>
<button id="secondtbutt" class="second">Second Gallery</button>
<button id="thirdbutt" class="third">Third Gallery</button>
<button id="fourthbutt" class="fourth">Fourth Gallery</button>

<img id="image1" class="first" .../>
<img id="image2" class="second".../>
<img id="image3" class="third".../>
<img id="image4" class="fourth".../>

然后,您可以使用jQuery相应地隐藏/显示组:

$(".first").show();

这样,您就可以在按钮和相关图像之间建立关联。

答案 1 :(得分:0)

您可以使用索引:

$(document).ready(function(){
    var buttons = $('button');
    var images = $('img');

    buttons.each(function(){
        $(this).on('click', function(){
            images.each(function(){$(this).hide();});
            images.eq($(this).index()).show();
        });
    });
});

这是一个FIDDLE:http://jsfiddle.net/me8sy4pw/