2013-11-24 96 views
0

我试图在点击单个链接时更改图像的src(我只有3个)。jQuery - 如何点击链接时通过数组循环?

所以,如果我点击链接#1,src会发生变化,如果我点击链接#2它会变成别的东西,有点像基本的图像滑块。

下面是一个简单的例子:http://jsfiddle.net/BVmUL/164/

jquery的我尝试:

var images = [ 
    "http://lorempixel.com/400/200/", 
    "http://linenwoods.com/images/kitten.png", 
    "http://linenwoods.com/images/third.png" 
], 
    links = $("ol.list-inline > li > a"), 
    img = $("figure > img"); 

links.each(function(){ 
    links.click(function(){ 
     img.prop("src", images[links.index()]); 
     console.log($(this).index()); // only gives back 0 instead of 0,1,2 like 
             // I expected ... 
    }); 
}); 

我怎么可以做这样的事情的使用jQuery?

回答

3

锚位于LI元素内部并且没有兄弟,因此它们的索引始终为零。

var images = [ 
    "http://lorempixel.com/400/200/", 
    "http://linenwoods.com/images/kitten.png", 
    "http://linenwoods.com/images/third.png" 
], 
    links = $("ol.list-inline > li > a"), 
    img = $("figure > img"); 


    links.on('click', function(){ 
     img.prop("src", images[$(this).closest('li').index()]); 
    }); 
}); 

获得指数(父李,而不是

+0

啊,这是有道理的)..谢谢大家的响应速度快!将在9分钟内接受。 – Anon

+0

我忘了问:我可以在代码中轻松添加'fadeIn()'或'fadeOut()',以便在img更改时添加淡入淡出效果? – Anon

+0

@Anon - 当然,像这样 - > http://jsfiddle.net/BVmUL/165/ – adeneo