Forgive me, it's been a while since figuring out anything with jQuery, I need some guidance/help: I'd love to swap an image 00x-a for 00x-b, but not just for a single image, but for many. Once the BTN below an IMG is clicked, I'd love to swap the IMG above for 00x-b while resetting other IMGs to 00x-a.
<div>
<img id="swap_this" src="img-001-a.jpg">
<a class="button">Change-IMG</a>
</div>
<div>
<img id="swap_this" src="img-002-a.jpg">
<a class="button">Change-IMG</a>
</div>
<div>
<img id="swap_this" src="img-003-a.jpg">
<a class="button">Change-IMG</a>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
$(".button").click(function(){
$("#swap_this").attr()({
"src":"img-001-b.jpg";
})
})
});
</script>
CodePudding user response:
This should do it.
You need the class swap_this
var arr = ['img-001-b.jpg', 'img-002-b.jpg', 'img-003-b.jpg']
$.each($('.swap_this'), function(index, value) {
$(this).attr('src', arr[index])
console.log($(this).attr('src'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img class="swap_this" src="img-001-a.jpg">
<a class="button">Change-IMG</a>
</div>
<div>
<img class="swap_this" src="img-002-a.jpg">
<a class="button">Change-IMG</a>
</div>
<div>
<img class="swap_this" src="img-003-a.jpg">
<a class="button">Change-IMG</a>
</div>
CodePudding user response:
Tried to follow up on your answer, but ended up with something else. The below does what I need, but can it be written with "each" or using a for-loop to iterate through? Thx.
// clicking btn_100
$('.btn_100').click(function(e) {
// reset all IMG to version -a.gif..
$(".img_100").attr('src','img-100-a.gif');
$(".img_099").attr('src','img-099-a.gif');
$(".img_098").attr('src','img-098-a.gif');
// set IMG_100 ver -b.gif..
$(".img_100").attr('src','img-100-b.gif');
});
// clicking btn_099
$('.btn_099').click(function(e) {
// reset all IMG to version -a.gif..
$(".img_100").attr('src','img-100-a.gif');
$(".img_099").attr('src','img-099-a.gif');
$(".img_098").attr('src','img-098-a.gif');
// set IMG_100 ver -b.gif..
$(".img_099").attr('src','img-099-b.gif');
});
// and so on..
CodePudding user response:
Maybe this could work…
for(a=1; a<=100; a ) {
// create fns for all btns
$(".btn_" a).click(function(e) {
// reset all IMG to version -a.gif..
for(i=1; i<=100; i ) {
$(".img_0" i).attr("src","image-0" i "-a.gif");
}
// set specific IMG to version -b.gif..
$(".img_" a).attr("src","image-" a "-b.gif");
});
}