我需要一种列出元素的data-*
属性的方法。我本来会使用Object.keys(element.dataset)
,但是IE 9.0不支持dataset
。那么我应该如何做才能在IE 9.0(以及Chrome,Firefox和Safari)中实现这一点呢?
我需要一种列出元素的data-*
属性的方法。我本来会使用Object.keys(element.dataset)
,但是IE 9.0不支持dataset
。那么我应该如何做才能在IE 9.0(以及Chrome,Firefox和Safari)中实现这一点呢?
element.attributes
会给你一个包含元素所有属性的NamedNodeList
。
只需要检查属性名称是否以data-
开头即可。
var attributes = element.attributes,
i = attributes.length;
for (; i--; ){
if (/^data-.*/.test(attributes[i].name)) {
console.log(attributes[i].name);
}
}
我需要这个功能,但也需要访问密钥,所以我根据Andreas提供的解决方案编写了一个函数:
Element.prototype.dataset_simulated = function(){
var attributes = this.attributes;
var simulatedDataset = {};
for (var i = attributes.length; i--; ){
if (/^data-.*/.test(attributes[i].name)) {
var key = attributes[i].name.replace('data-', '');
var value = this.getAttribute(attributes[i].name);
simulatedDataset[key] = value;
}
}
return simulatedDataset;
};
要使用它,而不是使用 element.dataset
,您需要使用 element.dataset_simulated()
。
这里是示例链接
看起来 IE<8 也不支持 Element.prototype
,所以这可以简单地成为一个函数,用法如下:dataset_simulated(elem)
:
function dataset_simulated(elem){
var attributes = elem.attributes;
var simulatedDataset = {};
for (var i = attributes.length; i--; ){
if (/^data-.*/.test(attributes[i].name)) {
var key = attributes[i].name.replace('data-', '');
var value = elem.getAttribute(attributes[i].name);
simulatedDataset[key] = value;
}
}
return simulatedDataset;
};
你也可以尝试以下方法:
[dom_element].getAttribute('[your data-* attribute name]');