最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - incrementdecrement .data() in jQuery - Stack Overflow

programmeradmin9浏览0评论

Dom elements seems a perfect place to attach data that relates to that element, but accessing it is cumbersome code-wise, 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?

Dom elements seems a perfect place to attach data that relates to that element, but accessing it is cumbersome code-wise, 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?

Share Improve this question asked Apr 13, 2011 at 22:52 Billy MoonBilly Moon 58.6k27 gold badges148 silver badges244 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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 :)

发布评论

评论列表(0)

  1. 暂无评论