我有一个本地html文件,我用它来做笔记,我把它分成隐藏的部分,我可以通过点击页面顶部的按钮来单独访问.问题是,当我在更新页面内容后重新加载页面时,它会恢复到默认状态,即没有任何部分打开,我会丢失我的位置.我需要一种方法来保持页面的状态,但仍然更新内容重新加载(最好不要使用另一个按钮,因为滚动到顶部按下它失败的目的).

不幸的是,JavaScript不是我的专业领域,我找到的少数几个与我试图实现的目标类似的在线指南并没有很好地解释事情.

以下是我到目前为止拥有的相关代码.它满足了我自动隐藏我当前不使用的部分的需要,但在更新部分内容后重新加载页面时,它不会记住哪个部分是打开的.

超文本标记语言

/* Navigation menu */
<button onclick="openPage('1')">First Section</button>
<button onclick="openPage('2')">Second Section</button>
<button onclick="openPage('None')">Hide All Sections</button>

/* Sections of my notes */
<section id="1" class="tabcontent">
</section>

<section id="2" class="tabcontent">
</section>

CSS

.tabcontent {
    display: none; // Hides all sections by default
}

JavaScript

function openPage(pageName, elmnt) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none"; // Hide all other sections
  }
  document.getElementById(pageName).style.display = "block"; // Shows the section I specified
}

推荐答案

要执行所需的操作,您需要在页面加载之间的某个位置存储页面状态.LocalStorage将是实现这一目标的理想场所.以下是如何实现这一点的一个示例.

请注意,它在单击按钮时设置本地存储键,在单击Clear按钮时删除该键,并且还在页面首次加载时从本地存储中读取,以便显示最后显示的内容.

<button class="section-toggle" data-page="1">First Section</button>
<button class="section-toggle" data-page="2">Second Section</button>
<button class="hide-sections">Hide All Sections</button>

<section id="1" class="tabcontent">Section 1</section>
<section id="2" class="tabcontent">Section 2</section>
const sections = document.querySelectorAll('.tabcontent');

const showContent = id => {
  sections.forEach(section => section.style.display = section.id == id ? 'block' : 'none');
  localStorage.setItem('page', id);
}

// show on click
document.querySelectorAll('.section-toggle').forEach(button => {
  button.addEventListener('click', e => showContent(e.target.dataset.page));
});

// clear all on click
document.querySelector('.hide-sections').addEventListener('click', () => showContent());

// show on load
showContent(localStorage.getItem('page') || '');
.tabcontent {
  display: none;
}

这里有一个jsFiddle中的工作示例,因为代码片段被沙箱保护并拒绝访问本地存储.

Javascript相关问答推荐

如何才能拥有在jQuery终端中执行命令的链接?

为什么我的includes声明需要整个字符串?

docx.js:如何在客户端使用文档修补程序

我应该绑定不影响状态的函数吗?'

如何在mongoose中链接两个模型?

配置WebAssembly/Emscripten本地生成问题

Promise Chain中的第二个useState不更新

如何从html元素创建树 struct ?

Regex结果包含额外的match/group,只带一个返回

扩展类型的联合被解析为基类型

如何使用TypeScrip设置唯一属性?

AddEventListner,按键事件不工作

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

如何让SVG图标在被点击和访问后改变 colored颜色 ,并在被访问后取消点击时恢复到原来的 colored颜色 ?

如何在Java脚本中并行运行for或任意循环的每次迭代

如何在移动设备中使用JAVASSCRIPT移除点击时的焦点/悬停状态

JSX/React -如何在组件props 中循环遍历数组

Rails 7:在不使用导入映射的情况下导入Java脚本

错误400:当我试图在React中使用put方法时,该字段是必需的

鼠标进入,每秒将图像大小减小5%