HTML标记上的数据属性值被读取为数组而不是字符串

Data attribute value on HTML tag is being read as an array rather than a string

本文关键字:数组 字符串 读取 数据属性 HTML      更新时间:2023-09-26

我的HTML中有一个span标记。。。

<span id="span0" data-input="[1, 2, 3]">span tag 0</span>

当我用jQuery读取输入属性时。。。

inputString = $("#span0").data("input");

变量CCD_ 1是具有三个元素的数组。如何读取输入属性,使其存储为字符串"[1,2,3]",而不是数组?

提前感谢你的智慧!

使用attr()方法如下:

inputString = $("#span0").attr("data-input");

inputString = $("#span0").attr("data-input");
alert(typeof inputString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="span0" data-input="[1, 2, 3]">span tag 0</span>

您可以尝试vanilla-js。它速度更快,而且不会自动将字符串解析为数组。

例如,使用其中一个:

document.getElementById('span0').dataset.input;
document.getElementById('span0').getAttribute('data-input');

console.log(document.getElementById('span0').dataset.input);
<span id="span0" data-input="[1, 2, 3]">span tag 0</span>