Reputation: 18891
I am using jQuery .data
to store the number of clicks on an element. I can add to the value fine, but subtracting gives a NaN error. The value only increases. How can I fix this?
HTML:
<div data-click="0">Click here</div>
JS:
$("div").on("click", function(){
console.log('Current: '+$(this).data('click'))
$(this).data('click',$(this).data('click')+1);
setTimeout(function(){
$(this).data('click',$(this).data('click')-1);
console.log('After: '+$(this).data('click'))
},1000);
});
Fiddle: http://jsfiddle.net/bhmC9/
Upvotes: 1
Views: 184
Reputation: 761
You can also set the scope of this
within the function like so (by calling bind
):
$("div").on("click", function(){
console.log('Current: '+$(this).data('click'))
$(this).data('click',$(this).data('click')+1);
setTimeout(function(){
$(this).data('click',$(this).data('click')-1);
console.log('After: '+$(this).data('click'))
}.bind(this),1000);
});
Upvotes: 1
Reputation: 437336
When inside the setTimeout
callback, this
does not have the value you expect it to. Preserve it this way:
var that = this;
setTimeout(function(){
$(that).data('click',$(that).data('click')-1);
console.log('After: '+$(that).data('click'))
},1000);
In fact, $(this)
appears so many times in that snippet that caching it sounds like a good idea. In addition, it also eliminates the need for watching out what this
is:
var $this = $(this);
console.log('Current: '+$this.data('click'))
$this.data('click',$this.data('click')+1);
setTimeout(function(){
$this.data('click',$this.data('click')-1);
console.log('After: '+$this.data('click'))
},1000);
Upvotes: 10