用jquery删除多个html5数据属性 [英] Remove multiple html5 data-attributes with jquery

查看:152
本文介绍了用jquery删除多个html5数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以jquery api表示如下:


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


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

 < a title =titledata-loremIpsum =Ipsumdata-loremDolor =Dolor>< / a> 
$('a')。removeAttr('data-loremipsum');






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



    更多详细信息:
    $ b


    1. 我有(比方说.. 60)
      不同的数据属性,我想删除所有这些。


    2. 首选方法是仅定位包含单词 lorem 的数据属性。在这种情况下, lorem 始终是第一个单词。 (或者如果你计数 data -


    3. 另外我想保留所有其他属性完整



    解决方案

      //获取所有数据的数组
    var data = $(a)。data(),
    i;
    //获取所有键名
    var keys = $ .map(data,function(value,key){return key;});
    //循环访问键,如果键包含lorem,则删除该属性。
    for(i = 0; i< keys.length; i ++){
    if(keys [i] .indexOf('lorem')!= -1){
    $( a。)。removeAttr(data-+ keys [i]);


    小提琴:http://jsfiddle.net/Gpqh5/


    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 .removeAttr() to remove those.

    I have no problem removing a single data-attribute.

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


    The question is, how can I remove multiple data-attributes?

    More details:

    1. The starting point is that I have multiple ( let's say.. 60 ) different data-attributes and I want to remove all of them.

    2. Preferred way would be to target only those data-attributes that contain the word lorem. In this case lorem is always the first word. (or second if you count data-)

    3. Also I'd like to keep all the other attributes intact

    解决方案

    // 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]);
        }
    }
    

    Fiddle here: http://jsfiddle.net/Gpqh5/

    这篇关于用jquery删除多个html5数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆