如何使用 jQuery 将数组存储到 HTML5 数据属性中以及从中检索数组?

jqueryweb developmentobject oriented programming更新于 2025/9/8 4:37:17

要将数组存储到数据属性中以及从中检索数组,请使用 jQuery 中的 data() 方法。以下是语法 −

var anyVariableName= $('#yourIdName).data('yourJavscriptArrayName');

以下是 jQuery 代码 −

示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=
1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<div id="test" data-details='["My", "Name", "is", "John"]'></div>
<script>
   var value = $('#test').data('details');
   alert(value);
</script>
</body>
</html>

要运行上述程序,请将文件名保存为"anyName.html(index.html)",然后右键单击该文件。在 VS Code 编辑器中选择"使用实时服务器打开"选项。

输出

这将产生以下输出 −


相关文章