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

点击按钮在导航栏添加元素并将元素保存至localStorage

实现点击按钮添加导航栏元素并保存到localStorage

我帮你调整并完善了代码,实现点击按钮添加导航项,同时将这些项持久化存储在localStorage中,刷新页面后也不会丢失。另外注意jQuery的引用顺序必须在自定义脚本之前,否则会导致jQuery未定义的错误。

完整代码示例

HTML 部分

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="style.css">
  <!-- 先引入jQuery,再引入自定义脚本 -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <h1>Hello Plunker!</h1>
  <button id="addNavItem">添加新导航项</button>
  <div id="myHeader">
    <a style="float:left" href="index.html">Index</a>
    <a href="page1.html">Page1</a>
    <a href="page2.html">Page2</a>
  </div>
</body>
</html>

CSS 部分(可选,用于美化导航栏)

#myHeader {
  background-color: #f1f1f1;
  padding: 10px;
  margin-top: 20px;
}

#myHeader a {
  margin-right: 15px;
  text-decoration: none;
  color: #333;
}

#myHeader a:hover {
  color: #007bff;
}

button {
  padding: 8px 15px;
  cursor: pointer;
}

JavaScript 部分

$(document).ready(function() {
  // 从localStorage获取已保存的导航项,默认是空数组
  let navItems = JSON.parse(localStorage.getItem('navItems')) || [];

  // 渲染已保存的导航项到页面
  function renderNavItems() {
    navItems.forEach(item => {
      const newLink = $(`<a href="${item.url}">${item.text}</a>`);
      $('#myHeader').append(newLink);
    });
  }

  // 页面加载时先渲染已有的导航项
  renderNavItems();

  // 绑定添加按钮的点击事件
  $('#addNavItem').click(function() {
    // 让用户输入导航项的文本和链接(你也可以改成固定值或自定义表单)
    const navText = prompt('请输入导航项文本:');
    const navUrl = prompt('请输入导航项链接地址:');

    if (navText && navUrl) {
      // 创建新的导航链接元素
      const newLink = $(`<a href="${navUrl}">${navText}</a>`);
      // 添加到导航栏
      $('#myHeader').append(newLink);

      // 将新项存入数组并更新localStorage
      navItems.push({ text: navText, url: navUrl });
      localStorage.setItem('navItems', JSON.stringify(navItems));
    }
  });
});

关键逻辑说明

  1. localStorage 读写:
    • 用JSON.stringify把数组转成字符串存入localStorage(因为localStorage只能存储字符串)
    • 用JSON.parse读取并转成数组,默认值设为空数组避免首次加载报错
  2. 页面初始化渲染:页面加载时自动读取localStorage里的导航项,渲染到导航栏,保证刷新后数据不丢失
  3. 点击添加逻辑:通过弹窗获取用户输入(你可以替换成更友好的表单),创建DOM元素添加到页面,同时更新数组和localStorage

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:00:56