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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11962091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:54:19  来源:igfitidea点击:

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

javascripthtml

提问by Vlad Nicula

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. I know it might sound strange, but I'm trying something new here.

这对我正在启动的项目非常有用。有了这个,我可以加载所需的 js 模块并将它们链接到 dom。我知道这听起来可能很奇怪,但我正在尝试一些新的东西。

采纳答案by Mark Pieszak - Trilon.io

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/

回答by jfriend00

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.

您的问题的答案是 HTML 不支持同一属性的多个实例。您可能检索该属性的所有典型方法只会检索这三种方法中的一种。

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(";");

回答by Tadeck

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('#viewport').data('requires')在这里:http: //jsfiddle.net/3StZs/