I have some dynamic data in my <div>
element. Look at the sample below:
<div>345</div>
<div>3245</div>
When I click on the div element, the nested value will change.
var someVar = $(this).find(div);
someVar.empty();
someVar.append("<div>Number has changed</div>");
Sample:
<div>345</div>
<div>Number has changed</div>
And when I click again on the div, I need to return the previous value:
<div>345</div>
<div>3245</div>
Here's the question: How do I keep this value for returning the number every time I click on the div with changed text inside of it?
I have some dynamic data in my <div>
element. Look at the sample below:
<div>345</div>
<div>3245</div>
When I click on the div element, the nested value will change.
var someVar = $(this).find(div);
someVar.empty();
someVar.append("<div>Number has changed</div>");
Sample:
<div>345</div>
<div>Number has changed</div>
And when I click again on the div, I need to return the previous value:
<div>345</div>
<div>3245</div>
Here's the question: How do I keep this value for returning the number every time I click on the div with changed text inside of it?
Share Improve this question asked Jun 10, 2017 at 14:05 Lab LabLab Lab 80111 silver badges35 bronze badges 2- you can read jquery documentation here : api.jquery. – pheromix Commented Jun 10, 2017 at 14:09
-
you mean
$(this).find( "div" )
– Roko C. Buljan Commented Jun 10, 2017 at 14:16
2 Answers
Reset to default 2you need create some data
attribute store the previous value.The each time click get the data from attribute and restore the current text to attr like this data-prev
.No need to append .html()
is enought to toggle
updated
$('div').click(function(){
var prev=$(this).html();
$(this).html($(this).data('prev'));
$(this).data('prev',prev)
console.log($(this).data('prev'))
})
.nested{
color:red;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>345</div>
<div data-prev="<div class='nested'>Number has changed</div>">3245</div>
You can use jQuery 'data' method.
$( "div" ).data( "number", 1 )
Then read it with:
( $( "div" ).data( "number" ) )
Documentation: https://api.jquery./data/