Using a function to update a value within the data() method of jQuery sets the variable equivalent to the anonymous function, not the return value

后端 未结 3 369
-上瘾入骨i
-上瘾入骨i 2021-01-24 08:57

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         


        
3条回答
  •  花落未央
    2021-01-24 09:41

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

提交回复
热议问题