简体   繁体   English

HTML5 中是否可以有多个 data-{name} 属性?

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

Is there a way to get all 3 data values from this element?有没有办法从此元素中获取所有 3 个数据值?

 <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.有了这个,我可以加载所需的 js 模块并将它们链接到 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.您的问题的答案是 HTML 不支持同一属性的多个实例。 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.您可以在data-属性中使用更复杂的结构。

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/使用jQuery.data()证明jQuery.data()这种方式检索数组: jQuery('#viewport').data('requires') )在这里: 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/ http://jsfiddle.net/S7D2D/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM