在 HTML5 数据属性中存储和检索 javascript 数组 [英] store and retrieve javascript arrays into and from HTML5 data attributes
问题描述
如何将 javascript Array
存储在 HTML5 data
属性中?
我已经尝试了 JSON.stringify
阳离子和转义字符的所有变体.
存储数组并再次检索它的精确方法是什么?
注意
我使用 [ $("#firstSelectedElement").val(), $("#secondSelectedElement").val() ]
构建数组.我用 $("#storageElement").data('storeit')
检索 id="storageElement" data-storeIt="stuff"
.
我似乎永远无法将数据检索为真正的 Array
,只能检索字符的 Array
.
原来你可以使用元素 data
属性中的 html 转义字符来拥有类似 json 的数组(编码是引号):
<div id="demo" data-stuff='["some", "string", "here"]'>
然后在 javascript 中获得它,无需任何额外的魔法:
var ar = $('#demo').data('stuff');
检查这个fiddle.
已编辑(2017 年)
您不需要在 data
属性中使用 html 转义字符.
<div id="demo" data-stuff='["some", "string", "here"]'></div>
检查这个新的fiddle.
How can a javascript Array
be stored in an HTML5 data
attribute?
I've tried every variation of JSON.stringify
cation and escaping characters.
What is the precise method to store the array and retrieve it again?
note
I build the array with [ $("#firstSelectedElement").val(), $("#secondSelectedElement").val() ]
. I retrieve id="storageElement" data-storeIt="stuff"
with $("#storageElement").data('storeit')
.
I can never seem to retrieve the data as a true Array
, only an Array
of characters.
It turned out that you could use the html escaped characters in the element data
attribute to have json-like array (encoded are quotes):
<div id="demo" data-stuff='["some", "string", "here"]'></div>
And then in javascript get it without any additional magic:
var ar = $('#demo').data('stuff');
Check this fiddle out.
Edited (2017)
You don't need to use html escaped characters in the data
attribute.
<div id="demo" data-stuff='["some", "string", "here"]'></div>
Check this new fiddle out.
这篇关于在 HTML5 数据属性中存储和检索 javascript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!