You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用HTML、CSS、JavaScript实现创建按钮的持久化保存?

实现刷新后保留用户创建的按钮

要让用户创建的按钮在浏览器刷新后依然保留,我们可以利用浏览器的localStorage来持久化存储按钮的文本内容,页面加载时再从存储中读取数据并重新渲染按钮。

以下是修改后的完整代码:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Create a button</h1>
Button name:<input id="buttoname" type="text"><br>
<button onclick="create()">Create Button</button>

<script>
// 页面加载时初始化已保存的按钮
function init() {
  // 从localStorage获取已保存的按钮列表,没有则初始化为空数组
  const savedButtons = JSON.parse(localStorage.getItem('customButtons')) || [];
  savedButtons.forEach(buttonText => {
    createButton(buttonText);
  });
}

// 创建单个按钮的复用函数
function createButton(text) {
  const button = document.createElement("button");
  button.innerHTML = text;
  document.body.appendChild(button);
}

// 修改后的创建按钮函数
function create(){
  const input = document.getElementById("buttoname");
  const buttonText = input.value.trim();
  // 空值不创建
  if (!buttonText) return;
  
  // 创建按钮
  createButton(buttonText);
  
  // 更新存储的按钮列表
  const savedButtons = JSON.parse(localStorage.getItem('customButtons')) || [];
  savedButtons.push(buttonText);
  localStorage.setItem('customButtons', JSON.stringify(savedButtons));
  
  // 清空输入框
  input.value = '';
}

// 页面加载完成后执行初始化
window.onload = init;
</script>
</body>
</html>

关键逻辑说明:

  • init函数:页面加载时触发,读取localStorage中保存的按钮文本数组,循环调用createButton重新生成按钮。
  • createButton函数:封装按钮创建逻辑,避免重复代码,接收文本参数直接生成按钮。
  • create函数:获取输入框的有效文本,创建按钮后,将文本添加到存储数组中并更新localStorage,同时清空输入框提升体验。

内容的提问来源于stack exchange,提问作者Axolotl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 02:01:15