问题
I have a div where dynamic data- attributes get added on some tags. (name of data- attributes to be generated dynamically by script, so there is no way my script will know the NAME of data-attribute)
<div data-1223="some data" data-209329="some data" data-dog="some value"> </div>
Now, I want to write a code in which it resets the div by removing all the data attributes and their values.
I can use
$('div').attr('data-209329',"")
but the problem is I don't know the name of data-attribute that will be added. the data-attribute that will be added is dynamic and I don't have control of it.
removing div and reinserting div is not an option. Pls help. thanks in advance
回答1:
YOu can use like this
var data = $("div").data();
var keys = $.map(data, function (value, key) {
return key;
});
for (i = 0; i < keys.length; i++) {
$("div").removeAttr("data-" + keys[i]);
}
Fiddle
Edit
Suggested by @Mottie
$.each($('div').data(), function (i) {
$("div").removeAttr("data-" + i);
});
Demo
回答2:
You can use this code :
var data = $('div').data();
for(var i in data){
//for change
$('div').attr("data-"+i,"something");
//for remove
$("div").removeAttr("data-" + i);
}
The $('div').data();
prepare a list of all data attributes in var data
variable.
Then you can work with it.
This is fiddle of this solution.
UPDATE Suggested by @Mottie
$.each($('div').data(), function (i) {
//for change
$('div').attr("data-"+i,"something");
//for remove
$("div").removeAttr("data-" + i);
});
回答3:
I think that the removeData() function is what you are looking for here. This will remove all data
information stored on the element.
The .removeData() method allows us to remove values that were previously set using .data(). When called with the name of a key, .removeData() deletes that particular value; when called with no arguments, all values are removed. Removing data from jQuery's internal .data() cache does not affect any HTML5 data- attributes in a document; use .removeAttr() to remove those.
It will not however remove the actual attributes from the elements. In order to remove the actual attributes, you'll need to extract a list of the existing attributes. You could do this by inspecting the data()
function of an element (before running removeData
).
The data()
function will return an object of key => value
pairs that you can then use to remove the actual attributes from the element using removeAttr().
来源:https://stackoverflow.com/questions/24059268/removing-all-dynamic-data-attributes-of-an-element