jQuery Data vs Attr?

前端 未结 3 1762
轻奢々
轻奢々 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:39

    You can use data-* attribute to embed custom data. The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.

    jQuery .data() method allows you to get/set data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

    jQuery .attr() method get/set attribute value for only the first element in the matched set.

    Example:

    foo
    
    $("#test").attr("title");
    $("#test").attr("data-kind");
    $("#test").data("kind");
    $("#test").data("value", "bar");
    

提交回复
热议问题