jQuery中的增减.data() [英] increment/decrement .data() in jQuery

查看:91
本文介绍了jQuery中的增减.data()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dom元素似乎是附加与该元素相关的数据的理想场所,但是从代码角度来看,访问它很麻烦,而且效率也很低.

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

是否有一种更快的方法来增加存储在jQuery对象.data()中的数字?

Is there a faster way to increment a number stored in the .data() of a jQuery object?

推荐答案

更好:

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:

直接使用对象获取或设置值要比单独调用.data()来获取或设置每个值要快.

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;
}

正如@Zirak指出的那样,如果您定期进行此调用,则插件可能是最佳选择:

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

可用于:

$('#the-thing').inc('counter', 1);
$('#the-thing').inc('counter', -1);

我知道inc不是一个好的方法名称,因为它表明您只能增加值.但我想不出更好的方法....我很乐意提出建议:)

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

这篇关于jQuery中的增减.data()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆