What's the difference between jquery's data(key,val) and attr(data-key,data-val)

前端 未结 1 744
北荒
北荒 2021-01-24 18:42

If you try to change a data attribute value with data() method you don\'t get the same result as attr(data-key, data-value) method.

For examp

1条回答
  •  旧时难觅i
    2021-01-24 19:22

    .data() is used to store data in an object, but as of the "release" of HTML5, it can also access data-* attributes on elements.

    However, it can not change these, as it is primarily used for storing data in objects etc, not physically on elements.

    Therefore attr() is the only way to change a value of an attribute on an element, such as data-* attributes.

    See:

    • jQuery Data vs Attr?
    • http://api.jquery.com/jQuery.data/
    • http://api.jquery.com/attr/

    0 讨论(0)
提交回复
热议问题