如何使用 JavaScript 中的 LocalStorage 在单击时更改按钮文本?
javascripthtmlfront end technology
JavaScript 是一种著名的编程语言,与 HTML 和 CSS 一起是万维网 (WWW) 的核心语言之一。它允许程序员捕获事件并修改文档对象模型 (DOM)。在本文中,我们将了解如何利用 JavaScript 在 localStorage 的帮助下在单击按钮时更改按钮的文本。
localStorage
localStorage 是窗口界面的只读属性,允许用户存储数据。保存的信息在浏览器会话之间保留。
localStorage 属性类似于 sessionStorage,但问题是即使页面会话已结束,数据仍会保留。
我们可以使用 getItem() 方法获取 localStorage 项目。它具有以下语法:
localStorage.getItem('key');
我们还可以设置 localStorage 项目。这可以使用 setItem() 方法完成。它具有以下语法:
localStorage.setItem('key','value');
示例
步骤 1:首先,我们将定义 HTML 代码。
<!DOCTYPE html> <html> <head> <title>How to change a button text on click using localStorage in Javascript?</title> </head> <body> <h4>How to change a button text on click using localStorage in Javascript?</h4> <div> <button id="main">CLICK ME!</button> </div> </body> </html>
步骤 2:现在我们将借助 CSS 为元素提供一些样式。
<style> #main { width: 20%; height: 50px; border-radius: 10px; } </style>
步骤 3:现在我们将编写单击按钮时更改文本的逻辑。
<script> let button=document.getElementById('main'); localStorage.setItem('buttonText','CLICKED!'); button.onclick=function(){ button.textContent=localStorage.getItem('buttonText'); } </script>
以下是完整代码:
<!DOCTYPE html> <html> <head> <title>How to change a button text on click using localStorage in Javascript?</title> <style> #main { width: 20%; height: 50px; border-radius: 10px; } </style> </head> <body> <h4>How to change a button text on click using localStorage in Javascript?</h4> <div> <button id="main">CLICK ME!</button> </div> <script> let button=document.getElementById('main'); localStorage.setItem('buttonText','CLICKED!'); button.onclick=function(){ button.textContent=localStorage.getItem('buttonText'); } </script> </body> </html>
结论
在本文中,我们了解了如何使用 localStorage 的 getItem() 和 setItem() 方法访问存储项。结合 onClick 事件的知识,我们能够在单击按钮元素时更改其文本。