jQuery Data vs Attr?

前端 未结 3 1753
轻奢々
轻奢々 2020-11-21 05:09

What is the difference in usage between $.data and $.attr when using data-someAttribute?

My understanding is that $.data

3条回答
  •  余生分开走
    2020-11-21 05:18

    The main difference between the two is where it is stored and how it is accessed.

    $.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

    $.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

    Data set with attr()

    • accessible from $(element).attr('data-name')
    • accessible from element.getAttribute('data-name'),
    • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
    • visible on the element upon inspection
    • cannot be objects

    Data set with .data()

    • accessible only from .data(name)
    • not accessible from .attr() or anywhere else
    • not publicly visible on the element upon inspection
    • can be objects

提交回复
热议问题