如何使用jQuery保存数据?

时间:2021-11-07 07:28:49

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.

当我单击div元素时,嵌套值将更改。

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时,我需要返回之前的值:

<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?

这是一个问题:每次点击内部更改文本的div时,如何保留此值以返回数字?

2 个解决方案

#1


2  

you 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

你需要创建一些数据属性存储前一个值。每次点击从属性获取数据并将当前文本恢复为attr,就像这样data-prev.No需要追加.html()是否应该切换

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.com/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>

#2


2  

You can use jQuery 'data' method.

您可以使用jQuery'data'方法。

   $( "div" ).data( "number", 1 )

Then read it with:

然后阅读:

  ( $( "div" ).data( "number" ) )

Documentation: https://api.jquery.com/data/

文档:https://api.jquery.com/data/

#1


2  

you 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

你需要创建一些数据属性存储前一个值。每次点击从属性获取数据并将当前文本恢复为attr,就像这样data-prev.No需要追加.html()是否应该切换

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.com/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>

#2


2  

You can use jQuery 'data' method.

您可以使用jQuery'data'方法。

   $( "div" ).data( "number", 1 )

Then read it with:

然后阅读:

  ( $( "div" ).data( "number" ) )

Documentation: https://api.jquery.com/data/

文档:https://api.jquery.com/data/