Javascript 如何在数据属性(HTML5)中设置JSON的属性
我有以下内容:Javascript 如何在数据属性(HTML5)中设置JSON的属性,javascript,jquery,json,custom-data-attribute,Javascript,Jquery,Json,Custom Data Attribute,我有以下内容: <div id="car" data-details='{ "color":"blue", "price":2000" }'></div> 但这需要同时设置“颜色”,我只想设置“price”属性。将JSON从数据属性中提取到变量,编辑变量,然后使用更新的变量重新设置属性 像这样的方法应该会奏效: <div id="car" data-details='{ "color":"blue", "price":2000 }'></div>
<div id="car" data-details='{ "color":"blue", "price":2000" }'></div>
但这需要同时设置“颜色”,我只想设置“price”属性。将JSON从数据属性中提取到变量,编辑变量,然后使用更新的变量重新设置属性 像这样的方法应该会奏效:
<div id="car" data-details='{ "color":"blue", "price":2000 }'></div>
// Pull the info from the data-details attribute into a variable called 'details'
var details = JSON.parse($('#car').attr('data-details'));
// Change the price property in our variable
details.price = 5000;
// Write the variable version of details back to the data-details
// attribute on the DOM element
$('#car').attr('data-details', JSON.stringify(details));
$("html").append($("#car").attr("data-details"));
//将“数据详细信息”属性中的信息拉入名为“详细信息”的变量中
var details=JSON.parse($('#car').attr('data-details'));
//更改变量中的price属性
详细信息。价格=5000;
//将详细信息的变量版本写回数据详细信息
//DOM元素上的属性
$('#car').attr('data-details',JSON.stringify(details));
$(“html”).append($(“#car”).attr(“数据详细信息”);
fiddle的更新版本:您可以创建两个数据属性,一个用于颜色,一个用于价格。获取属性值,解析值,更新对象的
price
属性,将其字符串化为JSON并设置元素的属性。如果你认为有更直接的方法,那就没有了。谢谢,你能更新我的JSFIDLE让我看看你是怎么做到的吗?谢谢,但这似乎不起作用。检查我的JSfidle以查看。.data
仅更新内部jQuery存储,而不是元素的属性。1。数据详细信息属性中的JSON字符串中存在语法错误。2.我以为你把所有的代码都粘贴到了问题中,没有看你的小提琴。我将更新我的响应修复了语法错误,仍然不知道如何设置属性?添加了一些注释,希望对您有所帮助
<div id="car" data-details='{ "color":"blue", "price":2000 }'></div>
// Pull the info from the data-details attribute into a variable called 'details'
var details = JSON.parse($('#car').attr('data-details'));
// Change the price property in our variable
details.price = 5000;
// Write the variable version of details back to the data-details
// attribute on the DOM element
$('#car').attr('data-details', JSON.stringify(details));
$("html").append($("#car").attr("data-details"));