1

我有两个用于图像库的数组。我在顶部有一个导航,其中包含我想要的不同画廊的 ID。我想这样做,以便当单击其中一个链接时,它会加载相应的数组并显示其中的图像。我的代码如下所示: HTML:

<div id="gallery>
   <div id="slideshow-container">
      <img src="images/someimg.jpg" id="current-img" />
   </div>
</div>

jQuery:

var gallery1 = ['images/img1.jpg', 'images/img2.jpg', 'images/img3.jpg'] 
var gallery2 = ['images/img4.jpg', 'images/img5.jpg', 'images/img6.jpg']

我正在使用教程制作图像幻灯片,因为我想远离插件,以便更好地掌握 jQuery 的工作原理。所以我的 jQuery 的其余部分看起来很相似:

编辑:我已将点击功能更改为@nullability 建议的功能,但我不确定如何将索引传递给该功能。我试图在每个函数中传递它的地方输入它,但在 ifif (i < index.length - 1){行我仍然收到一个错误,即索引未定义。

$(document).ready(function(){

setInterval(advanceImage, 4000)

})

//Creates array variable based on what user clicks
$('.nav li a').click(function(e) {
    e.preventDefault();
    var index = $(this).data('index');
    changeImage(index);
    //alert(gallery);
});

//Creates a current image from array
function currentImage(){
    i = jQuery.inArray($('#current-img').attr('src'), index);
    return i;
}

//Cycles through array
function advanceImage(){
    currentImage();
    if (i < index.length - 1){
        changeImage(i + 1);
    }else{
        changeImage(0)
    }
}

//Change current image to whatever i gives it
function changeImage(i){
$('#current-img').stop().animate({
    opacity: 0,
}, 200, function(){
    $('#current-img').attr('src', index);
    $('#slideshow-container img').load(function(){
        $('#current-img').stop().animate({
            opacity: 1,
        }, 200)
    })
})
}

我可以通过手动选择数组来显示和旋转图像,例如:gallery[0,0]或者gallery[0,1]但我不知道从哪里开始单击,即使读取单击的链接的 id 并创建一个我可以放入的变量。

编辑:我将其更改为两个单独的数组。我不能有这样的功能:

$('.nav li a').click(function() {
    var gallery = $(this).attr('id');
});

然后将图库放入其他代码以使其选择单击的内容?

4

1 回答 1

0

It sounds like your main issue is with your navigation buttons. You might want to use a data property on your links instead of the id attribute. For example, if you have the markup:

<ul class="nav">
    <li><a href="#" class="button" data-index="1">Slide 1</a></li>
    <li><a href="#" class="button" data-index="2">Slide 2</a></li>
    <li><a href="#" class="button" data-index="3">Slide 3</a></li>
</ul>

You can access the index data attribute by using jQuery data functions and use it to call your changeImage function like this:

$('.nav .button').click(function(e) {
    e.preventDefault();
    var index= $(this).data('index');
    changeImage(index);
});

Note that I included e.preventDefault(); to cancel the default action of clicking an <a> tag to avoid any unexpected behavior.

You can have multiple data attributes if you need to store additional array indexes. For example, you can use data-gallery in addition to data-index. Hope this helps.

于 2013-08-05T17:49:05.740 回答