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 365
-上瘾入骨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:38

    Basically your expectation is wrong.

    jQuery's .data does not modify the data attributes of the elements at all; it simply associates the data you provide with the element through a mechanism of its own choosing.

    The implementation is intentionally left unspecified, and .data does not process this data at all; you put something in, and when you later ask for it that is exactly what you get back. The data is totally opaque from jQuery's perspective.

    It's true that .data provides pre-population of an element's associated data from its HTML data- attributes as a convenience feature, but that is not its main mission. And of course the opaqueness of the data is still upheld in this case: when you ask for data, you get back exactly what was specified in the HTML.

提交回复
热议问题