increment variable according to numbers of clicks
I have following code:
javascript:
var counter = 0;
var totalItems = 8;
var restItems = $num-totalItems;
if (restItems==22) {
开发者_运维技巧$('#next').click(function(e) {
e.preventDefault();
counter++;
updatestatus();
});
}
function updatestatus() {
totalItems = totalItems + 8 * counter;
}
HTML:
<input type = "button" id="next" value="click me">
what I want is that before I click the button, the totoalItems is equal to 8, and each time when I click it, the totoal item is added by 8, but at the moment that bit of code dosen't work and give me a very large number, any one could help me figure it out, thanks a lot.
Why are you multiplying by the counter?
totalItems = totalItems + 8;
var counter = 0;
var totalItems = 8;
var restItems = $num - totalItems;
if (restItems == 22) {
$('#next').click(function(e) {
e.preventDefault();
counter++;
updatestatus();
});
}
function updatestatus() {
totalItems = totalItems + 8 * counter;
}
With this code, every time you run updatestatus()
, it increments totalItems
by its own value and 8 * counter
. You don't need to increment it:
function updatestatus() {
totalItems = 8 + 8 * counter;
}
But ideally, I'd just simplify the code:
var counter = 0;
var totalItems = 8;
var restItems = $num - totalItems;
$('#next').click(function(e) {
if (restItems == 22) {
e.preventDefault();
totalItems += 8;
}
});
精彩评论