简体   繁体   中英

Is it possible to have multiple data-{name} atributes in HTML5?

Is there a way to get all 3 data values from this element?

 <div id="viewport" 
    data-requires='js/base/paths'
    data-requires='js/base/dialog'
    data-requires='js/base/notifier'>

This would be really useful for a project that I am starting. With this I could load required js modules and link them to the dom. I know it might sound strange, but I'm trying something new here.

The answer to your question is that HTML does not support multiple instances of the same property. All the typical ways that you might retrieve that attribute will only retrieve one of the three.

The usual way to solve this problem is to use a single instance of the attribute and put multiple paths as the value. For paths, they are usually separated by semi-colons.

<div id="viewport" data-requires='js/base/paths;js/base/dialog;js/base/notifier'>

And, then use code to break up the multi-valued attribute into an array.

var requiredPaths = document.getElementById("viewport").getAttribute("data-requires").split(";");

You can use more complex structures within data- attributes.

Instead of this:

<div id="viewport" 
data-requires='js/base/paths'
data-requires='js/base/dialog'
data-requires='js/base/notifier'>

you can do this:

<div id="viewport"
data-requires='["js/base/paths", "js/base/dialog", "js/base/notifier"]'>
</div>

Proof using jQuery.data() (which just retrieves the array this way: jQuery('#viewport').data('requires') ) is here: http://jsfiddle.net/3StZs/

You could put them all in one if you separated them by something then split them up and put them in an Array.

var arrayData = document.getElementById('viewport').getAttribute('data-requries');
var arr = arrayData.split(',');

for (i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

http://jsfiddle.net/S7D2D/1/

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