如何使用jQuery批量删除页面中所有以data-sheets-开头的自定义属性
实现方案
核心思路是遍历全页所有DOM元素,逐个检查元素的属性列表,匹配前缀为data-sheets-的属性后执行删除,不受属性数量、名称的限制。
现代浏览器兼容写法
$('*').each(function () { const $current = $(this); // 把类数组的attributes转为数组遍历 [...this.attributes].forEach(attr => { if (attr.name.startsWith('data-sheets-')) { $current.removeAttr(attr.name); } }) })
全版本兼容写法(适配不支持ES6+语法的旧环境)
因为删除属性会动态修改attributes类数组的长度,所以采用倒序遍历避免漏处理属性:
$('*').each(function () { const $current = $(this); const attrs = this.attributes; // 倒序遍历属性集合 for (let i = attrs.length - 1; i >= 0; i--) { if (attrs[i].name.indexOf('data-sheets-') === 0) { $current.removeAttr(attrs[i].name); } } })
优化提示
如果已知data-sheets-属性只存在于部分元素下(比如示例中的span标签),可以把选择器$('*')替换为更精准的选择器(比如$('span')),减少遍历开销提升执行效率。
内容的提问来源于stack exchange,提问作者Vrajesh Doshi
相关产品推荐
相关产品推荐

