jQuery data函数的坑

这个函数

<div id="test" data-id="1e3"></div>
<script>
console.log($('#test').data('id'));
// 1e3  jQuery 1.9.1
// 1000  jQuery 1.7.2
</script>

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.

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. If the value isn't parseable as a JavaScript value, 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.

2014-07-16 23:02 更新

这个还是要看具体的jQuery版本而定的

jQuery.fn.jquery

我这测试,1.7.2 的是会自动转换的,1.9.1 是不会自动转换

而官方的文档的更新函数中,貌似并没有提及这一点

标签: none

已有 2 条评论

  1. justmore 小子,不知道如何称呼你,看了你好多篇博客,写的很好,你的工具也非常好。

    不过,你的代码中都转义了,比如本篇中的"等。

    。- 你能修改一下吗。。要不代码无法看。

    多谢哈。

    1. 恩,发现了,typecho 升级的原因,我会尽快修复插件

添加新评论