将 data-* 属性转换为对象 [英] Converting data-* attributes to an object
问题描述
我正在玩attr-data-* HTML5 的属性和相应的 javascript 数据集
I'm playing around with the attr-data-* attributes of HTML5 and the corresponding javascript dataset
我做了很多动态表单处理,所以我最终得到了这样的东西:
I'm doing alot of dynamic form processing, so I end up getting stuff like this:
<input data-feaux="bar" data-fizz="buzz"/>
由于 HTMLElement.dataset
返回一个 DOM 字符串映射
,所以我能弄清楚如何将其转换为本地对象的唯一方法是:
Since HTMLElement.dataset
returns a DOM string map
, the only way I can figure out how to convert it into an native object is:
var obj = JSON.parse(JSON.stringify(input_el.dataset))
有没有更好的方法来做到这一点?
Is there a better way to do this?
我为什么要这样做?假设我有很多很多这样的元素.我想遍历它们并将它们推入一个数组以供稍后处理,即
Why would I want to do this? Let's say I have many, many of these elements. I want to loop through them all and push them into an array for processing later, i.e.
elements = document.querySelectorAll("input")
my_data_array = []
for(var i = 0; i < elements.length; i++) {
my_data_array.push(elements[i].dataset)
}
现在我有一个对象数组,即我可以使用的 [{feaux: "bar", fizz:"buzz"}....]
.
Now I have an array of objects, i.e. [{feaux: "bar", fizz:"buzz"}....]
that I can work with.
但是,当我不将 DOM 字符串映射
转换为对象时,数组不会被填充(即上面的代码不起作用)
However, when I don't convert the DOM string map
into an object, the array doesn't get populated (i.e. the code above doesn't work)
编辑 2
仔细看,它实际上是一个DOM 字符串映射
,而不是一个object
.更正原始问题中的错别字以反映这一点.
Looking closer, it is actually a DOM string map
, not an object
. Correcting typos in the original question to reflect this.
推荐答案
您可以使用 Object.assign
Object.assign({}, element.dataset)
对于不支持 Object.assign 的浏览器,您可以使用 polyfill一个>
For browsers that doesn't support Object.assign you can use polyfill
这篇关于将 data-* 属性转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!