为什么 jquery 从数据 html5 属性中删除括号?

Why does jquery remove brackets from data html5 attribute?

我正在尝试使用 jquery 获取数据属性的内容,但返回的数据不是我设置的。

用这个简单的例子:

<div id="test" data-test="[1]"></div>

但是$('#test').data('test')returns1而不是[1]

使用纯javascript没有问题。

在线观看:https://jsfiddle.net/jojhm2nd/

jQuery 的 data is not an attribute accessor function. (This is a common mistake, easily made.) To just access the attribute, use attr.

$("#test").attr("data-test");

data 确实读取 data-* 属性,但只是为该元素初始化 jQuery 的数据缓存。 (而且它从不 写入 属性。)它会做一系列的事情,包括更改名称(例如,data-testing-one-two-three 变为 testingOneTwoThree)和解释值。在本例中,它将值解释为一个数组,因为它以 [ 开头。当您使用 alert 显示该数组时,它会被强制转换为字符串,而当您将数组强制转换为字符串时,它会执行 Array#join。例如,如果您的属性是 [1, 2],那么您会看到 1,2 作为结果。

来自上面链接的文档:

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.

jQuery 在您使用 .data 方法时发挥神奇作用。

来自 jQuery 网站:

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null).

您可以使用 .attr 方法并执行:

$('#test').attr('data-test');