使用jquery删除多个html5数据属性

问题描述 投票:14回答:7

所以jquery api说如下:

从jQuery的内部.data()缓存中删除数据不会影响文档中的任何HTML5数据属性;使用.removeAttr()来删除它们。

删除单个数据属性没有问题。

<a title="title" data-loremIpsum="Ipsum" data-loremDolor="Dolor"></a>
$('a').removeAttr('data-loremipsum');

问题是,如何删除多个数据属性?

更多细节:

  1. 起点是我有多个(比如说... 60)不同的数据属性,我想删除所有这些属性。
  2. 首选方法是仅定位包含单词lorem的数据属性。在这种情况下,lorem始终是第一个词。 (或者如果算上data-,则为第二个)
  3. 另外,我想保持所有其他属性不变
jquery html5 custom-data-attribute
7个回答
13
投票
// Fetch an array of all the data
var data = $("a").data(),
    i;
// Fetch all the key-names
var keys = $.map(data , function(value, key) { return key; });
// Loop through the keys, remove the attribute if the key contains "lorem".
for(i = 0; i < keys.length; i++) {
    if (keys[i].indexOf('lorem') != -1) {
        $("a").removeAttr("data-" + keys[i]);
    }
}

在这里小提琴:http://jsfiddle.net/Gpqh5/


5
投票

my jQuery placeholder plugin中,我使用以下内容来获取给定元素的所有属性:

function args(elem) {
    // Return an object of element attributes
    var newAttrs = {},
        rinlinejQuery = /^jQuery\d+$/;
    $.each(elem.attributes, function(i, attr) {
        if (attr.specified && !rinlinejQuery.test(attr.name)) {
            newAttrs[attr.name] = attr.value;
        }
    });
    return newAttrs;
}

请注意,elem是一个元素对象,而不是jQuery对象。

你可以很容易地调整它,只获得data-*属性名称:

function getDataAttributeNames(elem) {
    var names = [],
        rDataAttr = /^data-/;
    $.each(elem.attributes, function(i, attr) {
        if (attr.specified && rDataAttr.test(attr.name)) {
            names.push(attr.name);
        }
    });
    return names;
}

然后,您可以遍历结果数组,并为元素上的每个项调用removeAttr()

这是一个简单的jQuery插件,可以做到这一点:

$.fn.removeAttrs = function(regex) {
    return this.each(function() {
        var $this = $(this),
            names = [];
        $.each(this.attributes, function(i, attr) {
                if (attr.specified && regex.test(attr.name)) {
                        $this.removeAttr(attr.name);
                }
        });
    });
};

// remove all data-* attributes
$('#my-element').removeAttrs(/^data-/);
// remove all data-lorem* attributes
$('#my-element').removeAttrs(/^data-lorem/);

1
投票

下面的Vanilla JS清除所有数据属性。如果您想添加一些if逻辑来删除数据属性的子集,那么将该功能添加到下面的JavaScript应该是微不足道的。

function clearDataAttributes(el){
    if (el.hasAttributes()) {
        var attrs = el.attributes;
        var thisAttributeString = "";
        for(var i = attrs.length - 1; i >= 0; i--) {
            thisAttributeString = attrs[i].name + "-" + attrs[i].value;
            el.removeAttribute(thisAttributeString);
        }
    }
}

0
投票

我也会发布回答,因为我花了一些时间从Mathias帖子制作工作版本。

我遇到的问题是SVG需要额外的关注,没有什么细微差别(jQuery不喜欢它),但这里的代码也适用于SVG:

$.fn.removeAttrs = function(attrToRemove, attrValue) {
    return this.each(function() {
        var $this = $(this)[0];
        var toBeRemoved = [];
        _.each($this.attributes, function (attr) {
            if (attr && attr.name.indexOf(attrToRemove) >= 0) {
                if (attrValue && attr.value !== attrValue)
                    return;

                toBeRemoved.push(attr.name);
            }
        });

        _.each(toBeRemoved, function(attrName) {
            $this.removeAttribute(attrName);
        });
    });
};

请注意它是使用下划线,但你可以用$ .each替换_.each我相信。

用法:

svgMapClone
    .find('*')
    .addBack()
    .removeAttrs('svg-')
    .removeAttrs('context-')
    .removeAttrs('class', '')
    .removeAttrs('data-target')
    .removeAttrs('dynamic-cursor')
    .removeAttrs('transform', 'matrix(1, 0, 0, 1, 0, 0)')
    .removeAttrs("ng-");

0
投票

您可以循环特定元素的所有数据属性并过滤子字符串的索引。

REMOVE_ATTR我使用了.removeAttr()方法,但您可以根据数据属性的创建方式使用.removeData()方法。根据您的需要替换或组合。

 $.each($('div').data(), function (i) {
      var dataName = i, criteria = "lorem";
      if (dataName.indexOf(criteria) >= 0) { 
          $('div').removeAttr("data-"+dataName);
      }
 });

SET NULL您还可以选择将data-attribute设置为null,具体取决于您的业务逻辑。

$.each($('div').data(), function (i) {
    var dataName = i, criteria = "lorem";
    if (dataName.indexOf(criteria) >= 0) { 
       $('div').data(dataName, "");
    }
});

0
投票

使用jQuery方法removeData()

jQuery网站声明:

.removeData()方法允许我们删除先前使用.data()设置的值。使用键名称调用时,.removeData()将删除该特定值。在没有参数的情况下调用时,.removeData()会删除所有值。

这里的关键部分是:

在没有参数的情况下调用时,.removeData()会删除所有值。

https://api.jquery.com/removeData/


-3
投票

遗憾的是,在jQuery中不可能选择以给定值开头的属性名称(对于属性值,它是可能的)。

我想出的最简单的解决方案:

$(document).ready(function(){
    $('[data-loremIpsum], [data-loremDolor]').each(function(index, value) {
        $(this).removeAttr('data-loremIpsum')
               .removeAttr('data-loremDolor');
    });
});

JsFiddle Demo(确保在点击运行后查找html源代码)

© www.soinside.com 2019 - 2024. All rights reserved.