increment/decrement .data() in jQuery
Dom elements seems a perfect place to attach data that relates to that element, but accessing it is cumbersome code-w开发者_开发问答ise, and probably inefficient too.
Currently I am doing something like this to increment:
$('#the-thing').data({ counter: $('#the-thing').data('counter') + 1 })
Is there a faster way to increment a number stored in the .data() of a jQuery object?
Better:
var data = $('#the-thing').data();
data.counter += 1;
// `$('#the-thing').data().counter += 1` should work too
This avoids calling the data method twice. The documentation also says:
Using the object directly to get or set values is faster than making individual calls to .data() to get or set each value.
You could create a function if you really wanted to:
function add(sel, prop, val) {
var data = $(sel).data();
data[prop] += val;
}
As @Zirak points out, if you make this calls regularly, a plugin might be the best choice:
(function($) {
$.fn.inc = function(prop, val) {
return this.each(function() {
var data = $(this).data();
if(!(prop in data)) {
data[prop] = 0;
}
data[prop] += val;
});
}
}(jQuery))
which can be used with:
$('#the-thing').inc('counter', 1);
$('#the-thing').inc('counter', -1);
I know inc
is not a good method name as it suggests that you can only increase the value. But I could not think of something better.... I'm open for suggestions :)
精彩评论