As it's understandable from the code, I'm trying to create a simple img gallery.
I'm currently facing a calculation problem; if you run the snippet performing these actions you'll see what's wrong in the console log:
$ph_id
is not overwritten by the new id Can someone please explain me where the problem comes from? 'Cause I thought the code was written right but apparently I'm missing something.
[ EDIT ] I put the $('#next').click(function ()
and the $('#prev').click(function ()
outside of the $('.venus-div').click(function ()
and the problem at points 4. and 5. are now solved
$(document).ready(function () { $('.venus-div').click(function () { $this = $(this); $ph_id = $this.attr('id'); console.log('Current id: ' + $ph_id); }); $('#next').click(function () { $next_id = $ph_id++; console.log('Next id: ' + $next_id); }); $('#prev').click(function () { $prev_id = $ph_id--; console.log('Prev id: ' + $prev_id); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="venus-div" id="1" data-image="../img/bv.jpg"> <img src="../img/thumb/bv_thumb.jpg" class="venus-thumb"> </div> <div class="venus-div" id="2" data-image="../img/islamuj.jpg"> <img src="../img/thumb/islamuj_thumb.jpg" class="venus-thumb"> </div> <div class="venus-div" id="3" data-image="../img/vertical.jpg"> <img src="../img/thumb/vertical_thumb.jpg" class="venus-thumb"> </div> <div class="venus-div" id="4" data-image="../img/pano.jpg"> <img src="../img/thumb/pano_thumb.jpg" class="venus-thumb"> </div> <p id="prev">BACK</p> <p id="next">NEXT</p>
$next_id = $ph_id++;
sets $next_id
to the current value of $ph_id
and then increments $ph_id
by one. If you want the increment to happen first, you can place the ++
before the variable like so:
$next_id = ++$ph_id;
With this, $next_id
will be equal to the incremented $ph_id
.
The same applies to --
:
$prev_id = --$ph_id;
I think its because you are creating and binding every click a new click event in next and prev, and its triggering multiple times due to this multiple binding. You can either off these events or bind them outside the venus-div click function (making ph_id, next_id and prev_id global vars inside document ready.
I cant write coding from mobile, if you need i'll update it later :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.