如何将数组数据推送到数据属性

时间:2017-09-05 11:27:34

标签: javascript

我有一个div,如下所示

var mydiv = '<div  id="100" data-stuff="[]"></div>' ;

现在我有一个JSON数组

var vendoritemsdata = [{"name":"892_KK_0_KK_0tab1_checkbox","cost":10,"additionname":"t10","addtionid":69},{"name":"892_KK_1_KK_0tab1_checkbox","cost":11,"additionname":"t11","addtionid":70}];

我正在尝试将数组的每个元素推送到上面的数据属性内容

http://jsfiddle.net/cod7ceho/493/

1 个答案:

答案 0 :(得分:2)

您可以使用JQuery简单地设置元素的data-stuff属性。在此之前,您需要将JSON对象数组转换为字符串,因此请使用JSON.stringify()

&#13;
&#13;
var vendoritemsdata = [{"name":"892_KK_0_KK_0tab1_checkbox","cost":10,"additionname":"t10","addtionid":69},{"name":"892_KK_1_KK_0tab1_checkbox","cost":11,"additionname":"t11","addtionid":70}];

$('#100').attr('data-stuff', JSON.stringify(vendoritemsdata));

//retrieving
var dataStuff = $('#100').attr('data-stuff');
dataStuff = JSON.parse(dataStuff);
console.log('length is '+dataStuff.length);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div  id="100" data-stuff="[]">This is a div</div>
&#13;
&#13;
&#13;

检查元素This is a div并检查data-stuff属性是否包含数组值。

要检索该值,您需要解析字符串以获取JSON数组。