HOWTO · jQuery
jQuery 本地存储
本教程演示了如何在 jQuery 中使用本地存储。
本页内容
jQuery 不提供任何内置功能来处理本地存储,但我们可以将 JavaScript 本地存储方法与 jQuery 对象一起使用。本教程演示了如何通过 jQuery 使用本地存储。
jQuery 本地存储
JavaScript 中的 setItem() 和 getItem() 方法用于存储和从本地存储中获取数据;我们可以使用这些方法将 jQuery 对象存储在本地存储中,并从本地存储中获取对象。这些使用 jQuery 的方法的语法是:
var html = $('element')[0].outerHTML;
localStorage.setItem('DemoContent', html);
localStorage.getItem('htmltest')
其中 var html 将 jQuery 对象转换为 JavaScript 对象,将其存储到 localStorage,最后从 localStorage 获取,DemoContent 是键,html 变量是 setItem 方法。
让我们尝试一个示例来设置和获取从 jQuery 到 localStorage 的文本。参见示例:
<!DOCTYPE html>
<html>
<head>
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<title>jQuery Local Storage</title>
</head>
<body>
<h1>Delftstack | The Best Tutorial Site</h1>
<p id="DemoPara1">This is paragraph 1</p>
<button id="DemoButton1"> Click Here</button>
<script type="text/javascript">
$(document).ready(function () {
$("#DemoButton1").click(function () {
var TextContent = $('#DemoPara1').text();
localStorage.setItem('textcontent', TextContent);
alert(localStorage.getItem('textcontent'));
});
});
</script>
</body>
</html>
上面的代码会将段落的内容设置到本地存储并在警报框中获取。见输出:
现在让我们尝试使用 jQuery 设置和获取整个 HTML 对象到 localStorage。参见示例:
<!DOCTYPE html>
<html>
<head>
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<title>jQuery Local Storage</title>
</head>
<body>
<h1>Delftstack | The Best Tutorial Site</h1>
<p id="DemoPara1">This is paragraph 1</p>
<button id="DemoButton1"> Click Here</button>
<script type="text/javascript">
$(document).ready(function () {
$("#DemoButton1").click(function () {
var HTMLContent = $('#DemoPara1')[0].outerHTML;
localStorage.setItem('htmlcontent', HTMLContent);
alert(localStorage.getItem('htmlcontent'));
});
});
</script>
</body>
</html>
上面的代码将使用 $('#DemoPara1')[0].outerHTML; 将 jQuery 对象转换为 JavaScript 对象方法并将其存储到本地存储中,最后得到警报框中的对象。见输出: