Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 数据属性中的JSON对象_Javascript_Html_Json_Custom Data Attribute - Fatal编程技术网

Javascript 数据属性中的JSON对象

Javascript 数据属性中的JSON对象,javascript,html,json,custom-data-attribute,Javascript,Html,Json,Custom Data Attribute,我们可以在html数据标记属性中写入JSON字符串吗 然后在javascript中处理它,将其作为普通JSON对象进行解析 例如: HTML <select class="field" data-select="{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}"></select> 使用单引号的解决方案: <select class="field" data-sele

我们可以在html数据标记属性中写入JSON字符串吗

然后在javascript中处理它,将其作为普通JSON对象进行解析

例如:

HTML

<select class="field" data-select="{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}"></select>
使用单引号的解决方案:

<select class="field" data-select='{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}'></select>

使用JSON.stringify(如果是javascript)将JSON设置为字符串,并将其保存在data-*字段中

var json = {"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]};
var div = document.getElementById("myDiv");
div.setAttribute("data-json", JSON.stringify(json));
alert(div.getAttribute("data-json"))
检查模板引擎文档(如果您正在使用),以生成字符串化json


Fiddle:

只需在“数据选择”属性的包装字符串中使用单引号。
var json = {"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]};
var div = document.getElementById("myDiv");
div.setAttribute("data-json", JSON.stringify(json));
alert(div.getAttribute("data-json"))