Store JSON object in data attribute in HTML jQuery Ask Question

Store JSON object in data attribute in HTML jQuery Ask Question

I am storing data using the data- approach in a HTML tag like so:

<td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td>

I am then retrieving the data in a callback like this:

$(this).data('imagename');

That works fine. What I am stuck on is trying to save the object instead of just one of the properties of it. I tried to do this:

<td><button class='delete' data-image='"+results[i]+"'>Delete</button></td>

Then I tried to access the name property like this:

var imageObj = $(this).data('image');
console.log('Image name: '+imageObj.name);

The log tells me undefined. So it seems like I can store simple strings in the data- attributes but I can't store JSON objects...

I've also tried to use this kid of syntax with no luck:

<div data-foobar='{"foo":"bar"}'></div>

Any idea on how to store an actual object in the HTML tag using the data- approach?

ベストアンサー1

Actually, your last example:

<div data-foobar='{"foo":"bar"}'></div>

seems to be working well (see http://jsfiddle.net/GlauberRocha/Q6kKU/).

The nice thing is that the string in the data- attribute is automatically converted to a JavaScript object. I don't see any drawback in this approach, on the contrary! One attribute is sufficient to store a whole set of data, ready to use in JavaScript through object properties.

(Note: for the data- attributes to be automatically given the type Object rather than String, you must be careful to write valid JSON, in particular to enclose the key names in double quotes).

おすすめ記事