单击div时,从数组jQuery循环img src

时间:2014-01-30 21:35:01

标签: javascript jquery html arrays variables

我已经在堆栈交换和其他网站上阅读了无数的解决方案,但没有一个能为我工作。我希望div包含img,左侧有箭头。当你click箭头时,javascript应该将img src更改为图像数组中的下一个元素。我是javascript的新手,所以在撰写您的回复时请考虑这一点。谢谢。这是一个jfiddle http://jsfiddle.net/CZKAB/1/

这是html

<div id="filter-one" class="filter">
<div class="filter-nav">
<div id="prev-button"><img src="img/prv.png" alt="prev" title="Previous"></div>
</div>

<div id="filter-one-canvas">
<img src="img/shelter.png" id="filter-one-img" alt="filter1" title="Filter One">
</div>

<div class="filter-nav">
<a href="javascript:nextImage('#filter-one-img')" alt=""><img src="img/nxt.png" alt="next" title="Next"></a>
</div>
</div>

CSS

.filter {
height: 100px;  
}

.filter-nav {
height: 52px;
width: 52px;
border-radius: 100%;
background-color: rgba(0,204,0,1);
opacity: 0.7;
float: left;
margin-top: 24px;
}

#filter-one img {
float: left;
}

的Javascript

$(document).ready(function() {

var filterOneImages = new Array();

filterOneImages[0] = new Image();
filterOneImages[0].src = '../img/shelter.png';

filterOneImages[1] = new Image();
filterOneImages[1].src = '../img/food.png';

filterOneImages[2] = new Image();
filterOneImages[2].src = '../img/energy.png';

filterOneImages[3] = new Image();
filterOneImages[3].src = '../img/transport.png';

filterOneImages[4] = new Image();
filterOneImages[4].src = '../img/economy.png';

/*------------------------------------*/

function nextImage(element)
{
var img = document.getElementById(element);

for(var i = 0; i < filterOneImages.length;i++)
{
if(filterOneImages[i].src == img.src)
        {
if(i === filterOneImages.length){
document.getElementById(element).src = filterOneImages[0].src;
break;
}
document.getElementById(element).src = filterOneImages[i+1].src;
break;
}
}
}

$('div.filter-nav').mouseenter(function() {
$(this).fadeTo('fast', 1);
});
$('div.filter-nav').mouseleave(function() {
$(this).fadeTo('fast', 0.7);
});
});

1 个答案:

答案 0 :(得分:2)

您要更改包含src的{​​{1}}而不是div本身的img属性,请替换:

img

$("#filter-one-img").attr(...