I answered this question: Manipulate Custom Values with jQuery
With this jQuery:
$(\'img\').attr(\'u\', function(i,u) {
/* i is the index of the curr
If you need this capability, you can easily add it:
$.fn.fdata = function( name, callback ) {
return this.each( function( i, element ) {
var $element = $(element);
var data = callback( i, $element.data(name) );
$element.data( name, data );
});
};
Now you can use $(sel).fdata( name, callback );
and do what you want in the callback.
It may be tempting to extend the existing $().data()
method to add the callback capability, but as other pointed out, this would break any other code that depends on being able to store a function reference as data.
Of course, it's also possible that merely adding this .fdata()
method could break other code - if some other code on your page also tries to use the same method name in its own plugin. So it may be wiser to make this a simple function instead. The code is almost identical either way:
function updateData( selector, name, callback ) {
$(selector).each( function( i, element ) {
var $element = $(element);
var data = callback( i, $element.data(name) );
$element.data( name, data );
});
}