Created
December 12, 2012 10:58
-
-
Save charliepark/4266921 to your computer and use it in GitHub Desktop.
You can use arrays and hashes in HTML5 data attributes. Use JSON.parse, and make sure you're using single quotes around the brackets and double quotes inside the brackets.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> | |
</head> | |
<body> | |
<div id="animals" data-animals='["cat", "dog", "bird"]'></div> | |
<div id="vehicles" data-vehicles='{"motorcycle":"Harley", "car":"Herbie", "steamshovel":"Mike"}'></div> | |
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> | |
<script type="text/javascript" charset="utf-8"> | |
$(function(){ | |
var a = JSON.parse($('#animals').attr('data-animals'))[0]; | |
$('#animals').html(a); | |
var v = JSON.parse($('#vehicles').attr('data-vehicles')).car; | |
$('#vehicles').html(v); | |
}); | |
</script> | |
</body> | |
</html> |
You can indeed retrieve it via the jquery function data
, but if you do, you need to lose the data-
part of the data-attribute. So in the example:
var a = $('#animals').data('animals'); // not .data('data-animals')
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use the jquery function
data
instead of parse and attr: