How to remove the "date" we defined in jQuery?

1

In jQuery, you can set values for an attribute by data .

So:

$('body').data({id: 1, nome: 'stack'});

And the result would be:

console.log($('body').data()); // {id: 1, nome: 'stack'}

But if I want to rewrite the object, I can not do this with data .

$('body').data({nome: 'stack'});

console.log($('body').data()); // {id:1, nome: 'stack'}

Note that id was still there, even though I was resetting the date value.

How can I delete a value of data or the entire value of data in jQuery?

    
asked by anonymous 19.10.2015 / 16:13

2 answers

4

jQuery.removeData () allows you to remove values that were previously entered using jQuery.data ().

Let's take an example:

var div = $( "div" )[ 0 ];
$( "span:eq(0)" ).text( "" + $( "div" ).data( "test1" ) );
jQuery.data( div, "test1", "VALUE-1" );
jQuery.data( div, "test2", "VALUE-2" );
$( "span:eq(1)" ).text( "" + jQuery.data( div, "test1" ) );
jQuery.removeData( div, "test1" );
$( "span:eq(2)" ).text( "" + jQuery.data( div, "test1" ) );
$( "span:eq(3)" ).text( "" + jQuery.data( div, "test2" ) );
div {
    margin: 2px;
    color: blue;
  }
  span {
    color: red;
  }
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>
 
<div>value1 before creation: <span></span></div>
<div>value1 after creation: <span></span></div>
<div>value1 after removal: <span></span></div>
<div>value2 after removal: <span></span></div>
</body>
    
19.10.2015 / 16:20
3

The $.data , when called with a single argument of type object, does not assign a single value - assigns several. There is a match between the individual attributes set by jQuery and the data-* attributes in HTML:

document.body.innerHTML += JSON.stringify($("#teste").data());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste" data-foo="10" data-bar="20" data-baz="30"></div>

% w / o without parameters is a "shortcut" to access all attributes at once. O with a parameter of type object, a shortcut to assign several. But to access each one individually, it is necessary to use the method with a first string argument (the name of the desired attribute):

var el = $("#teste");
document.body.innerHTML += JSON.stringify(el.data()) + "<br>";
el.data("foo", 40);
document.body.innerHTML += JSON.stringify(el.data()) + "<br>";
el.removeData("bar");
document.body.innerHTML += JSON.stringify(el.data()) + "<br>";

document.body.innerHTML += el.data("baz");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste" data-foo="10" data-bar="20" data-baz="30"></div>
    
19.10.2015 / 16:31