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 363
-上瘾入骨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:45

    The difference between data and many of the other jquery functions (such as attr and many others) is that data can store any type of object. attr can only store string values. Because of this, it is completely valid to want to store a function using data.

    If the jquery team were to make a similar signature for data, they would need to somehow distinguish between wanting to store the function and wanting to evaluate the function. It would likely get too confusing so they just did not include the ability to execute the function.

    I think the best you can do is to use each.

提交回复
热议问题