jQuery 本地儲存

Sheeraz Gul 2024年2月15日
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 本地儲存文字

現在讓我們嘗試使用 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 物件方法並將其儲存到本地儲存中,最後得到警報框中的物件。見輸出:

jQuery 本地儲存 HTML

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook