【问题标题】:Selected and remove all matching data attributes选择并移除所有匹配的数据属性
【发布时间】:2014-05-25 00:40:03
【问题描述】:

我正在尝试找到一种方法来从页面中删除来自不同类型元素的所有匹配数据属性。

我现在循环一个数组,但是名称列表太长了,因此我希望有更好的方法来删除我的自定义数据属性.....使用正则表达式模式?

// 代码

var dataArr  = ['data-myplugin-value',
                'data-myplugin-id',
                 ...
                 ...
                 ...
                 ...
                'data-myplugin-name'];

$.each(dataArr, function(i,a){
   $('['+a+']').removeAttr(a);  
});

【问题讨论】:

  • 如何得到数组?
  • 简单,我自己创建数组 ;-)

标签: javascript jquery regex


【解决方案1】:

如果您不介意使用 XPath,这是我的解决方案:

function removeMyDataAttributes() {
    var list, iterator, attribute, i, n;

    // Select all attribute nodes that it's name starts with "data-myplugin-"
    iterator = document.evaluate('//*/attribute::*[starts-with(local-name(), "data-myplugin-")]', 
                    document.documentElement, null, XPathResult.ANY_TYPE, null);
    list = [];
    while ((attribute = iterator.iterateNext())) {
        list.push(attribute);
        // Note: can't call removeAttributeNode here: 
        // InvalidStateError: Failed to execute 'iterateNext' on 'XPathResult': The document has mutated since the result was returned.
    }
    for (i = 0, n = list.length; i < n; ++i) {
        attribute = list[ i ];
        attribute.ownerElement.removeAttributeNode(attribute);
    }
}

【讨论】:

    【解决方案2】:

    如果元素共享一个共同的父元素,那么您可以将搜索范围缩小到该元素:

    var holder = $('#containerid');
    $.each(dataArr, function(i,a){
        $('['+a+']', holder).removeAttr(a);  
    });
    

    这个SO topic 有一些代码使用attributes 集合,但我不相信它会更有效。

    【讨论】:

    • 如果合适,您可以考虑将属性值设置为 '' 或某个任意值 'xxx',而不是完全删除该属性。但我将此作为评论,因为我怀疑差异可以忽略不计。
    【解决方案3】:

    你认为你上面写的会起作用吗?您将 dataArr 视为 DOM 元素,这是错误的。 jQuery 将无法找到

    $('['+a+']').removeAttr(a);

    因为 'a' 不指代元素。

    现在,关于如何解决它 - 我需要一个帮助 - 这些数据属性是从 jquery 或 html 5 的一部分输入的。如果是通过 jquery,那么你可以使用

    http://api.jquery.com/jquery.removedata/.

    它会起作用的。因此遍历所有 DOM 元素并调用 removeData()。不是最好的解决方案,但会起作用。

    【讨论】:

    • 我的例子确实有效。但应该有更好、更清洁的方法来做到这一点。
    • 哦,好吧。那我去找找:)
    【解决方案4】:
    Loop through the array and remove all data attributes  
    $.each(dataArr, function(i,a){
       removeDataAttributes('[+a+]');  
    });
    
    // removes all data attributes from a target element
    // example:  removeDataAttributes('#user-list');
    function removeDataAttributes(target) {
    
        var i,
            $target = $(target),
            attrName,
            dataAttrsToDelete = [],
            dataAttrs = $target.get(0).attributes,
            dataAttrsLen = dataAttrs.length;
    
        // loop through attributes and make a list of those
        // that begin with 'data-'
        for (i=0; i<dataAttrsLen; i++) {
            if ( 'data-' === dataAttrs[i].name.substring(0,5) ) {
                // Why don't you just delete the attributes here?
                // Deleting an attribute changes the indices of the
                // others wreaking havoc on the loop we are inside
                // b/c dataAttrs is a NamedNodeMap (not an array or obj)
                dataAttrsToDelete.push(dataAttrs[i].name);
            }
        }
        // delete each of the attributes we found above
        // i.e. those that start with "data-"
        $.each( dataAttrsToDelete, function( index, attrName ) {
            $target.removeAttr( attrName );
        })
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 2015-05-27
      • 1970-01-01
      • 2016-06-01
      • 2016-11-22
      • 2021-11-06
      • 2017-06-14
      相关资源
      最近更新 更多