Why is jQuery automatically parsing my data-* attributes?

后端 未结 1 607
醉梦人生
醉梦人生 2020-12-21 01:52

I just noticed that if I try to read an html5 data-* attribute using .data it will parse automatically, whereas reading the value using .attr

相关标签:
1条回答
  • 2020-12-21 02:24

    Quote from the documentation:

    As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

    For example, given the following HTML:

    <div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

    All of the following jQuery code will work.

    $("div").data("role") === "page";

    $("div").data("lastValue") === 43;

    $("div").data("hidden") === true;

    $("div").data("options").name === "John";

    Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

    So it seems that since jQuery 1.6 the .data method parses the values.

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