我是 javascript 编程新手,并且对数据属性检索感到困惑。
下面的链接对于使用 jQuery 的人来说有点有用
store and retrieve javascript arrays into and from HTML5 data attributes
我想对 vanilla js 做同样的事情。在自定义数据属性的帮助下,我想创建对象和数组。
<div id="getAnimation"
data-r="564"
data-c="96"
data-custom="x:0;y:0;z:0;rotationX:0;rotationY:0;rotationZ:0;scaleX:0.75;scaleY:0.75; skewX:0;skewY:0;opacity:0;transformPerspective:600;transformOrigin:50% 50%;"
data-s="700"
data-st="1400"
</div>
Do HTML5 custom data attributes “work” in IE 6?
上面的链接有助于很好地获取数据属性,但如何过滤数据自定义中的字符串或直接创建数据自定义对象。
如果有人知道有一个图书馆可以这样做,请告诉我
最佳答案
这里有几个快速函数,可让您存储、检索和删除任何支持 JSON 的数据到数据属性
function setData(node, data_name, data_value) {
node.dataset[data_name] = JSON.stringify(data_value);
}
function getData(node, data_name) {
return JSON.parse(node.dataset[data_name]);
}
function delData(node, data_name) {
return delete node.dataset[data_name];
}
然后将一个数组写入data-fizz中的#getAnimation
// variables to use
var elm = document.getElementById('getAnimation'),
foo = [1, 2, 3, 'a', 'b', 'c'];
// store it
setData(elm, 'fizz', foo);
// retrieve it
var bar = getData(elm, 'fizz');
// look what we have
console.log(bar); // [1, 2, 3, "a", "b", "c"]
需要IE 11+,因为我使用node.dataset
,如果将其更改为所使用的方法 node.setAttribute
、node.getAttribute
和 node.removeAttribute
,则要求降至 IE 8+ 因为 JSON.stringify
和 JSON.parse
关于javascript - 数据属性检索和解析 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25686365/