JavaScript incrementing a variable
I'm trying to increment a variable in JavaScript by clicking on a link, it works the first time but then every other time if I click on it once it will show up 3 times, then 4, 5 and so on. A screenshot of the console:
The numbers in the blue (right) are as expected, there is nothing wrong with this开发者_如何转开发 but as you can see on the left, each line is one click. the first log is fine but then it logs 1 three times, then 10 four times.
Here is the code thats doing the work.
$('.here').live('click', function(eve) {
eve.preventDefault();
var curpop = $(this).attr('rel')
++curpop
$('.pop').html(curpop);
console.log(curpop)
})
$(this).attr('rel')
is just a number (in the blue, right, in the picture) once you click the link it is meant to increment the number.
Thanks for you help.
EDIT: I have set up the same thing in jsfiddle but it seems to work there, and all the suggestions still dont work on my project even though they should.
<h4 class='left'>Click
<a class="here" href="#" rel="1">here</a></h4>
<h4 class='right'>
<span class='pop'>
1
</span>
</h4>
This is the html, now there are multiple of these but are loaded via ajax, I am guessing that it would have something to do with the multiple instances of the class with no identifier to separate them?
More EDIT As I suspected the problem was with the "multiple instances of the class with no identifier to separate them" so I just made each one like this:
<span id="<?php echo $thereID; ?>_span" class='pop'>
1
</span>
then
$('#' + thereID + '_span').html(curpop);
Thanks for all the help
Need to see more code, but typically I see JS beginners adding the event inside of the event. In other words, every time the link is clicked, another event handler is added.
At any rate, here's an example of incrementing a counter in a click handler: http://jsfiddle.net/GSuSk/
<a href="#" id="link">GO UP</a>
<p>0</p>
<script>
$('#link').click(function(){
var v=$('p').text();
$('p').text(+(v)+1);
});
</script>
Why dont you try this kind of method? Look here for demo
Not sure with this limited amount of code, but if I'm not mistaken, I think one problem is that the variable is being created within live and really should initialize outside so that it only needs grab it once, then increment from there on without having to grab the new value each time. Here is how I re-arranged it. http://jsfiddle.net/robx/nDbb8/1/
<script type="text/javascript">
$(function(){
$('.here li a').click(function(){
var current = parseInt($(this).attr('rel'));
var inc = current + 1;
console.log(inc);
$(this).attr('rel',inc);
});
});
</script>
<div >
<ul class='here'>
<li><a href='#' rel="1">one</a></li>
<li><a href='#' rel="10">two</a></li>
<li><a href='#' rel="37">three</a></li>
<li><a href='#' rel="1">four</a></li>
</ul>
</div>
I don't think you need the live function here ... the key is to use parseInt to cast the current value of the rel attribute as it's being evaluated as a string ... :-)
精彩评论