简体   繁体   中英

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. 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] . You keep your data in the data-attribute with wrong syntax. Try first make your value of data-image into JSON format and then keep in the data-image attribute. 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. You can get and set the HTML data-* attribute using HTMLElement.dataset

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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