jQuery .data()无法检索数据-*。

10

我正在使用IE8测试。 我刚刚将jQuery从v1.5.2升级到v1.6.1,现在数据方法不起作用了。

这行看起来像这样:

<tr class="ui-widget-content alt" nodeIndex="2" data-DocAttributeFieldType="TextBox" data-DocClassAttributeFieldId="60777" jQuery16106588245076914028="66">

这个有效:

$("#docClassAttributeFields tbody tr:first").attr("data-DocClassAttributeFieldId");

这个不起作用:

$("#docClassAttributeFields tbody tr:first").data("DocClassAttributeFieldId");

它里面有一个错误吗?

这是一个例子。在1.5.2和1.6中运行它,看看它们的表现有何不同... http://jsfiddle.net/5hbKX/

1个回答

16

来自文档(我怀疑1.6中提到的更改有问题 - 你尝试过去掉大小写,看看lastValue示例吗?)

HTML 5 data- Attributes

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. When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

根据上述HTML5规范

自定义数据属性是指没有命名空间的属性,其名称以字符串"data-"开头,在连字符后至少有一个字符,与XML兼容,并且不包含U+0041到U+005A(拉丁大写字母A到拉丁大写字母Z)范围内的任何字符。

在HTML文档中,HTML元素上的所有属性都会自动转换为ASCII小写,因此ASCII大写字母的限制不会影响这些文档。


有趣的一点是,如果你在Firebug(FF)和Firebug-lite(IE)中查看源代码,data-*会变成小写,但在IE开发人员工具中查看时,它是混合大小写。 - Homer
6
如果不允许使用大写字母,则使用连字符代替连接单词。 - Betamos
2
好的,这会让人有点困惑,如果有连字符,大写字母就有效。所以,.data("id-D")是有效的,而.data("idB")则无效...http://jsfiddle.net/5hbKX/2/ - Homer
现在我明白了... 3. 对于列表中的每个名称,对于名称中的每个后跟在 U+002D 连字符 (-) 后面且处于 U+0061 到 U+007A 范围内(U+0061 拉丁小写字母 a 到 U+007A 拉丁小写字母 z)的字符,删除 U+002D 连字符 (-),并将其后面的字符替换为相同的字符 转换为 ASCII 大写字母 - Homer
有没有一种方法可以保留连字符? - Timo Huovinen
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接