开发者

jQuery .data() : possible to increment (++ or --)?

Whats the best way to increment a 开发者_Go百科value in a jQuery .data() object?


This looks a bit odd, but according to the docs .data() returns all data fields as an object, so you can change its value directly:

$('#id').data('counter', 0);

Both options work:

$('#id').data().counter++;
$('#id').data()['counter'] += 5;

Retrieving the data return the expected value:

alert($('#id').data('counter')); // 6


Or, if you control what you are storing, store an object reference so you can modify the values on the object directly using ++:

var $elem = $('<div>');
$elem.data('something', {value:1});
$elem.data('something').value++;

console.log($elem.data('something').value); // 2


var data = parseInt ($.data("data-attr")) + 1;

$.data("data-attr",data);


I think you will have to read the value and write it back, so:

$(element).data('yourKey', $(element).data('yourKey') + 1);

After all, data() is a function call, and incrementing the result will not modify the value itself, which sits in an internal jQuery data structure.


It's as simple as increasing a variable, just store the .data() value, increment it and store it back in.

Let's say you have a number set in the NumbeR data variable.

var myNumber = $(selector).data('NumbeR');
$(selector).data('NumbeR', myNumber++)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜