15

したがって、jquery api は次のように述べています。

jQuery の内部 .data() キャッシュからデータを削除しても、ドキュメント内の HTML5 data- 属性には影響しません。それらを削除するには、.removeAttr() を使用します。

単一のデータ属性を削除しても問題ありません。

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

問題は、複数のデータ属性を削除するにはどうすればよいですか?

詳細:

  1. 出発点は、複数(たとえば.. 60 ) の異なるデータ属性があり、それらすべてを削除したいということです。

  2. 好ましい方法は、単語を含むデータ属性のみをターゲットにすることloremです。この場合lorem、常に最初の単語です。(または、カウントする場合は 2 番目data-)

  3. また、他のすべての属性をそのまま維持したいと思います

4

7 に答える 7

5

私の 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/);
于 2012-01-23T08:35:24.650 に答える
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-");
于 2016-04-07T22:10:25.410 に答える