要在浏览器的本地存储(如localStorage或sessionStorage)中存储一个字符串,你可以使用以下方法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>本地存储字符串</title>
</head>
<body>
<input type="text" id="myString" placeholder="请输入字符串">
<button onclick="storeString()">提交</button>
<script src="script.js"></script>
</body>
</html>
script.js
),然后编写以下代码以处理按钮点击事件,将字符串存储到localStorage:function storeString() {
// 获取输入框中的字符串
var myString = document.getElementById('myString').value;
// 将字符串存储到localStorage,使用一个键(如'myKey')来标识这个字符串
localStorage.setItem('myKey', myString);
}
// 获取存储在localStorage中的字符串
var myString = localStorage.getItem('myKey');
// 在控制台输出字符串
console.log(myString);
这样,当你点击提交按钮时,页面上的字符串将被存储到本地存储中。你可以在其他页面或稍后时间读取并使用这个字符串。
领取专属 10元无门槛券
手把手带您无忧上云