为什么jQuery不删除所有数据属性
Why does jQuery not remove all the data attributes?
正如标题所说:为什么jQuery不删除所有数据属性?
<div data-subject-name="Spanisch" data-subject-id="9" data-subject-alias="Spa" data-category-id="1"></div>
$.fn.removeAttrs = function(regex) {
var regex = new RegExp(regex, "g");
return this.each(function() {
var _this = $(this);
console.log(this.attributes);
$.each(this.attributes, function(i, attrib){
console.log(attrib);
if (attrib && attrib.specified && regex.test(attrib.name)) {
console.log(attrib.name);
_this.removeAttr(attrib.name);
}
});
});
};
$('div').removeAttrs('^(data-)');
这是 http://jsfiddle.net/g2pXt/8/
我正在使用从 jquery 中删除多个 html5 数据属性@Mathias Bynens 但它不起作用。 那么这个解决方案有什么问题呢?
实际上,您的代码有两个问题,每个问题都部分掩盖了另一个问题。
" test
在同一全局正则表达式实例上多次调用,将超越前一个匹配项。"因此,每隔一次使用相同的正则表达式执行.test
时,它不会从字符串的开头进行搜索。我用str.search(regex)>=0
替换了regex.test(str)
来解决这个问题。
此外,您的脚本似乎存在索引问题,因为您在循环中间删除了属性。我相信这是因为"具有长度属性的数组和类似数组的对象......按数字索引迭代,从 0 到 length-1。在循环解决问题后一次性删除所有属性(.removeAttr()
将接受要删除的属性的空格分隔列表。
$.fn.removeAttrs = function(regex) {
var regex = new RegExp(regex, "g");
return this.each(function() {
var _this = $(this);
var removethese = '';
$.each(this.attributes, function(i, attrib){
if (attrib && attrib.specified && attrib.name.search(regex)>=0) {
removethese += ' '+attrib.name;
}
});
_this.removeAttr(removethese);
});
};
http://jsfiddle.net/mblase75/YHyjC/
请注意,以这种方式使用 .removeAttr()
实际上是第二次重复循环,因此为了获得最大效率,您应该重新调整代码并使用向后计数并同时删除this.attributes
的 for
循环。但是,对于单个简短的属性集,性能提升将微乎其微。
$.fn.removeAttrs = function(regex) {
var regex = new RegExp(regex, "g");
return this.each(function() {
var _this = $(this);
for (var i=this.attributes.length-1; i>=0; i--){
var attrib = this.attributes[i];
if (attrib && attrib.specified && attrib.name.search(regex)>=0) {
_this.removeAttr(attrib.name);
}
}; // end for
});
};
http://jsfiddle.net/mblase75/Zm4qR/
您的内部循环正在迭代在其下方更改的项目列表。
最安全的方法是使用直 JS 循环,从属性列表的末尾向后,这样在删除前一个元素时不会跳过元素:
for ( var i = this.attributes.length - 1; i >= 0; --i ) {
var attrib = this.attributes[i];
if (attrib && attrib.specified && regex.test(attrib.name))
{
console.log(attrib.name);
_this.removeAttr(attrib.name);
}
}
更新了 jsFiddle,包括简化的正则表达式:http://jsfiddle.net/g2pXt/36/
- 序列化数据属性中对象的最可靠方法
- jQuery最近父级的数据属性选择器
- delete在Object上效率低下,但在DOM Element's的数据属性,与null out相比
- 数据属性仅在切换设备模式下工作
- 函数jquery.html()不提供数据属性集值
- 在数据属性上进行下拉自动选择
- JavaScript-获取数据属性的值返回未定义的值
- 如何替换数据属性中的特定字符串单词
- 使用数据属性将HTML数据复制到另一个元素
- 带有CSS的数据属性就没那么有用了
- jQuery:从数据属性中删除除前4个字符外的所有字符
- 如何使用jquery按数据属性删除li标签
- 在向用户呈现数据之前删除 JSON 内容/删除 JavaScript 对象属性
- 按数据属性查找和删除项目
- 为什么jQuery不删除所有数据属性
- 如何使用HTML数据集属性删除data-*属性
- jquery:通过指定数据属性删除元素
- 选中并删除所有匹配的数据属性
- 使用 jQuery 验证插件 1.11.1 动态添加/删除具有数据属性的表单验证
- 从脚本标记中找到特定的数据属性并删除脚本标记