Reputation: 12529
Is it bad practice to do this in a template, or is there a better alternative? Is it okay to have an empty span like this in my code?
<span class="stored-id-number" data-idnumber="1234"><!-- empty --></span>
The reason I ask is because this currently seems to be the only way that I can store some data about multiple items that each live in a different template structure, and then reliably retrieve that data with JavaScript, like so:
// get all instances of this data item - where ever they may be
$('.stored-id-number').each(function (item) {
var idNumber = $(this).data('idnumber');
// do something with ID number in relation to this item
});
I seemed to me strange to add an empty span
element just to store some data. But at the moment it seems like the only reliable way that I can do it.
Upvotes: 2
Views: 383
Reputation: 13211
It is designed for this in HTML5.
More about data-*
here: http://www.w3schools.com/tags/att_global_data.asp
Alternatively you could do:
<script>
var store = {
"myStoreId": 1234,
"myOterStoreId": 9876,
}
</script>
Access it by:
store["mystoreId"]
or
for (storeId in store) {
var idNumber = store[storeId]
}
EDIT: Maybe you simple want an Array of "storeIds" ? Do it like that:
<script>
var store = [
1234,
9876,
]
</script>
Access it by:
store[index]
or
for (var i = 0; i < store.length; ++i) {
var idNumber = store[0]
}
Upvotes: 2