Remove multiple html5 data-attributes with jquery

后端 未结 7 1146
清酒与你
清酒与你 2020-12-16 14:25

So jquery api says the following:

Removing data from jQuery\'s internal .data() cache does not effect any HTML5 data- attributes in a document; use .

7条回答
  •  臣服心动
    2020-12-16 14:39

    In my jQuery placeholder plugin, I’m using the following to get all the attributes for a given element:

    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;
    }
    

    Note that elem is an element object, not a jQuery object.

    You could easily tweak this, to get only data-* attribute names:

    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;
    }
    

    You could then loop over the resulting array, and call removeAttr() for each item on the element.

    Here’s a simple jQuery plugin that should do the trick:

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

提交回复
热议问题