为什么jQuery不删除所有数据属性

Why does jQuery not remove all the data attributes?

本文关键字:数据属性 删除 jQuery 为什么      更新时间:2023-09-26

正如标题所说:为什么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.attributesfor 循环。但是,对于单个简短的属性集,性能提升将微乎其微。

$.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/