简体   繁体   中英

Is it best practice to store data in HTML tags that don't have any content?

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.

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]
}

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