为什么jQuery会自动解析我的data- *属性? [英] Why is jQuery automatically parsing my data-* attributes?
问题描述
我刚注意到,如果我尝试使用 .data
读取html5 数据 - *
属性,它将解析自动,而使用 .attr
读取值不会。
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
will not.
data-id="00123456"
- 实例这里。
- Live example here.
为什么这是默认行为?我有某些对象,其字段在字符串中是数字值,例如00123456,而不是123456。
Why is this the default behavior? I have certain objects whose fields are of numeric values within a string, e.g. "00123456" and not 123456.
我错过了一个jQuery 更新日志
备忘录或者是什么?
Did I miss a jQuery changelog
memo or what?
推荐答案
来自文档的引用:
从jQuery 1.4.3开始,HTML 5数据属性将自动引入jQuery的数据对象
。使用
嵌入破折号处理属性在jQuery 1.6中已更改为符合W3C HTML5
规范。
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.
例如,给定以下HTML :
For example, given the following HTML:
< div data-role =pagedata-last-value =43data-hidden =truedata-选项= '{ 名称: 约翰}' >< / DIV>
以下所有jQuery代码的将工作。
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;
每次尝试都将字符串转换为JavaScript值
(这包括布尔值,数字,对象,数组和null),否则
将其保留为字符串。要将值的属性检索为字符串
而不尝试转换它,请使用attr()方法。
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.
所以似乎从jQuery 1.6开始, .data
方法会解析这些值。
So it seems that since jQuery 1.6 the .data
method parses the values.
这篇关于为什么jQuery会自动解析我的data- *属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!