简体   繁体   English

如何使用jquery检索数据属性值是一个对象数组

[英]How to retrieve data-attribute value of which is an array of objects with jquery

我的data-attribute看起来像这样:

data-image="[object Object],[object Object] "

Only string/number can be stored in attributes. 只有字符串/数字可以存储在属性中。 So just store the src of the image if you want to store image details. 因此,如果要存储图像详细信息,只需存储图像的src即可。 If for some reason you want to store an object, convert it to string first and then later when you retrieve it, convert to object. 如果由于某种原因您想要存储对象,请先将其转换为字符串,然后在检索时将其转换为对象。

//Convert to String 
var mystring = JSON.stringify(myobject); // store this in the attribute. 

//Convert to Object while retrieving 
var myobj = JSON.parse(mystring);

Actually when you retrieve this, you will get only string with value [object Object],[object Object] . 实际上,当你检索它时,你将只获得值为[object Object],[object Object]字符串。 You keep your data in the data-attribute with wrong syntax. 您使用错误的语法将data-attribute保存在data-attribute Try first make your value of data-image into JSON format and then keep in the data-image attribute. 首先尝试将data-image值设置为JSON格式,然后保留data-image属性。 After that you can retrieve your data via (see comments) 之后,您可以通过(请参阅注释)检索您的数据

 const dataArray = [ { name: 'Name1' }, { name: 'Name2' } ]; const div = $('#div'); div.data('image', JSON.stringify(dataArray)); // keep the attribute as string const retrievedDataImageAsJSON = div.data('image'); // retrieve the data attribute as string const dataObj = JSON.parse(retrievedDataImageAsJSON); // parse from JSON into JS objects. console.log(dataObj); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='div' data-image> </div> 

If the data-* attribute is set at HTML use valid JSON for the value, JSON.stringify() and JSON.parse() to set and get the data-* attribute value as a JavaScript object. 如果data-*属性设置为HTML,则使用值JSON.stringify()JSON.parse()有效JSON来设置并获取data-*属性值作为JavaScript对象。 You can get and set the HTML data-* attribute using HTMLElement.dataset 您可以使用HTMLElement.dataset获取和设置HTML data-*属性

 console.log( JSON.parse( document.querySelector("div").dataset.image ) ) 
 <!-- set `data-*` attribute value as valid `JSON` --> <div data-image='[{"a":123}, {"b":456}]'></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM