简体   繁体   English

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

[英]cycle img src from array jQuery when div is clicked

I have read countless solutions on stack exchange and other websites and none of them are working for me. 我在堆栈交换和其他网站上阅读了无数解决方案,但没有一个对我有用。 I want a div containing an img , with arrows either side. 我想要一个包含imgdiv ,两侧div一个箭头。 When you click the arrows, the javascript should change the img src to the next element in an array of images. 当您click箭头时,javascript应将img src更改为图像数组中的下一个元素。 I am new to javascript so please consider this when writing your response. 我是javascript新手,因此在撰写回复时请考虑这一点。 Thanks. 谢谢。 Here is a jfiddle http://jsfiddle.net/CZKAB/1/ 这是一个jfiddle http://jsfiddle.net/CZKAB/1/

Here is the html 这是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 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 使用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);
});
});

You are changing the src attribute of the div containing the img and not the img itself, replace: 您正在更改包含img而不是img本身的divsrc属性,请替换:

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

with

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM