jQuery Data vs Attr
When working with data attributes, there are two primary jQuery methods you can use: $.data and $.attr. Understanding their differences is crucial for effective data storage and retrieval.
$.attr for HTML5 Data-Attributes
If you're dealing with HTML5 data-attributes, such as <a>, the appropriate method is $.attr. This enables you to read and write data-attributes directly from the element's HTML. For instance:
$('#foo').attr('data-foo'); // Outputs: "bar" $('#foo').attr('data-foo', 'baz'); // Updates the attribute to "baz"
$.data for Arbitrary Data Storage
In contrast, $.data allows you to store arbitrary data on an element, unrelated to specific attributes. This data is not accessible via HTML, but rather through the jQuery cache. It's often used for widget instantiation and storing complex objects. For example:
$('#foo').data('myData', {key: 'value'}); $('#foo').data('myData').key; // Outputs: "value"
Hyphens and CamelCase in $.data
When using $.data, hyphenated data attribute names are automatically converted to camelCase, while the original hyphenated format remains available in HTML. However, using hyphens in JavaScript is not recommended for access via $.data().
Auto-Casting in $.data
Another useful feature of $.data() is its ability to auto-cast values. If the value matches a recognized pattern, it will be converted to the appropriate data type. This simplified pattern:
<a>
Can be accessed as:
$('#foo').data('num'); // Outputs: 15 $('#foo').data('bool'); // Outputs: true $('#foo').data('json'); // Outputs: {fizz: ['buzz']}
When to Use $.attr vs $.data
Generally, use $.attr for accessing HTML5 data-attributes that require direct interaction with HTML. Use $.data for storing arbitrary data not accessible through HTML, especially when working with complex objects.
The above is the detailed content of jQuery $.attr() vs. $.data(): When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!