简体   繁体   English

如何从一个类的所有实例中删除所有数据属性

[英]how to remove all data attributes from all instances of a class

Need to remove all data attributes from .title . 需要从.title删除所有 data属性。

 $('button').on('click', function(){ $('.title').removeAttr('data'); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title' data-w = 960 data-x = 'gold'>lorem</div> <div class='title' data-w = 540 data-x = 'silver'>ipsum</div> <div class='title' data-w = 720 data-x = 'sun'>lorem</div> <br> <button>CLICK</button> 

Doesn't work. 不起作用 Another try: 另一种尝试:

$('.title').removeAttr('data-w', 'data-x');

Removes only the first one ( data-w ) 仅删除第一个( data-w

Any help? 有什么帮助吗?

You can get all the keys from data and then remove data-key . 您可以从数据中获取所有keys ,然后删除data-key

 $('button').on('click', function(){ var keys = Object.keys($("div").data()); keys.forEach(key =>{ $('.title').removeAttr(`data-${key}`); }) console.log(Array.from(document.querySelectorAll('.title'))); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title' data-w = 960 data-x = 'gold'>lorem</div> <div class='title' data-w = 540 data-x = 'silver'>ipsum</div> <div class='title' data-w = 720 data-x = 'sun'>lorem</div> <br> <button>CLICK</button> 

Check below code. 检查以下代码。

       $("#button").click(function(){
            $(".title").each(function() {                       
                var titleElement = $(this);
                $.each(titleElement.data(), function(i){
                    titleElement.removeAttr('data-'+i);
                });
            }); 
        });

I have tested it and it is working fine. 我已经对其进行了测试,并且工作正常。 Check working example: https://codepen.io/rohitmittal/pen/WPdKzj 检查工作示例: https : //codepen.io/rohitmittal/pen/WPdKzj

You can use the following code to accomplish that: 您可以使用以下代码完成此操作:

 $('button').on('click', function() { var titleClasses = $('.title'); titleClasses.each(function() { $(this).removeAttr('data-x') .removeAttr('data-w'); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title' data-w=9 60 data-x='gold'>lorem</div> <div class='title' data-w=5 40 data-x='silver'>ipsum</div> <div class='title' data-w=7 20 data-x='sun'>lorem</div> <br> <button>CLICK</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM