jQuery removeAttribute() not working
-
26-10-2019 - |
문제
I have been searching desperately for an answer to this question, but not found anything. I am currently improving the code on a website I'm creating, switching from ,,custom'' attributes to the HTML5 data-yyy attributes. Now heres my problem.
$("#test ul li").click(function(event){
$(this).toggleClass("selected");
if($(this).hasClass("selected")){
if(jQuery.trim($("#input_value").val())){
$(this).data("special",{"value":jQuery.trim($("#input_value").val())});
}
}
else{
$(this).removeAttr("data-special");
}
});
The following code is fired when a certain li-element is clicked. A class is toggled, and after the toggling (is that a word?) the script checks if this element has the toggled class or not. If it does not have the class (that's where the problem is), the script should remove the attribute "data-special", deleting the data. This does not happen at all!
If add
$("#test ul li").removeAttr("data-special");
outside the function, it's all fine and works as expected. Any ideas?
해결책
You've imported the data-special
value into .data()
, so use .removeData()
.
$(this).removeData("special");
Once you've imported an attribute value into .data()
, you need to work with it there. Removing the attribute doesn't remove the .data()
.
If you needed them both removed, then you'd need to call both methods, or simply don't use .data()
in the first place.
다른 팁
This isn't an attribute
$(this).data("special",{"value":jQuery.trim($("#input_value").val())});
Your are storing this in the jquery cache. therefore if you want to remove it you have to do as the other poster indicated and use the removeData function to eliminate it.