gpt4 book ai didi

javascript - 选择并删除所有匹配的数据属性

转载 作者:数据小太阳 更新时间:2023-10-29 05:33:24 25 4
gpt4 key购买 nike

我正在尝试找到一种方法来从页面中删除来自不同类型元素的所有匹配数据属性。

我现在循环一个数组,但名称列表太长了,我希望有更好的方法来删除我的自定义数据属性......使用正则表达式模式?

//代码

var dataArr  = ['data-myplugin-value',
'data-myplugin-id',
...
...
...
...
'data-myplugin-name'];

$.each(dataArr, function(i,a){
$('['+a+']').removeAttr(a);
});

最佳答案

如果您不介意使用 XPath,这是我的解决方案:

function removeMyDataAttributes() {
var list, iterator, attribute, i, n;

// Select all attribute nodes that it's name starts with "data-myplugin-"
iterator = document.evaluate('//*/attribute::*[starts-with(local-name(), "data-myplugin-")]',
document.documentElement, null, XPathResult.ANY_TYPE, null);
list = [];
while ((attribute = iterator.iterateNext())) {
list.push(attribute);
// Note: can't call removeAttributeNode here:
// InvalidStateError: Failed to execute 'iterateNext' on 'XPathResult': The document has mutated since the result was returned.
}
for (i = 0, n = list.length; i < n; ++i) {
attribute = list[ i ];
attribute.ownerElement.removeAttributeNode(attribute);
}
}

关于javascript - 选择并删除所有匹配的数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23850984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com