Skip to content Skip to sidebar Skip to footer

How To Increment Jquery Variable?

I'm trying to browse through a picture gallery with jquery, so I have a button which is supposed to increment a variable by 1 and then use that to load the next picture. Using the

Solution 1:

How can I get x to persist after the function it is set in?

Try defining x outside of and before click handler

var x = 1;
$("body").on("click", function() {
  x = x + 1;
  $(this).html(x)
})
body {
  width: 300px;
  height: 300px;
  border: 1px solid purple;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
click

Solution 2:

Your code looks ok. and here's a working version https://jsfiddle.net/a50nz178/1/

A couple of things you could check:

  • check that the image is actually there /1.JPGas well
  • check that images are not all named as jpg all lower case?

Solution 3:

If I had to guess, looking at your previousYou've updated. Turns out I was right. Your x was out of scope. correct code, I'd bet your problem is scope. Scope Tutorial

I'm willing to bet, somewhere else in your code your using something like for(x in ; ... Which is reassigning x. If that's not the case, I'd still bet on either scope, or the image is src isn't correct. You should use your developer console to check if a bad image source is being pulled. Your using / at the begining of your img src which will go back to base path. If you images are in an images folder you need to include the proper directory path.

You could easily shorten the scope of this by attaching your increment variable to your element object like so:

$("#browse-right").click(function(e) {
    //  the following is a simple inline `if` statement//  what it says is (this is your element)//  if this.i does not exist, create it equal to one, //  else count it up once
    !this['i'] ? this.i=1: this.i++;
    $("#pic").html('<img src="/' + this.i + '.JPG" />');
    //  the following simply shows what `i` currently is
    $('h3').text(this.i);
});
p { cursor: pointer; background: #aabb00; padding: 1em .5em; text-align: center; }
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><pid="browse-right">Browse Right</p><h3></h3><divid="pic">
  IMG HERE
</div>

Post a Comment for "How To Increment Jquery Variable?"