Javascript 如何为多个页面存储和加载同一段代码?
所以,我正在研究一个“标签”系统。因此,每当我单击按钮时,就会添加一个新选项卡 每个选项卡都应该重定向到一个新网站,tab1重定向到tab1.html,tab2重定向到tab2.html等等 我的问题是:Javascript 如何为多个页面存储和加载同一段代码?,javascript,html,jquery,Javascript,Html,Jquery,所以,我正在研究一个“标签”系统。因此,每当我单击按钮时,就会添加一个新选项卡 每个选项卡都应该重定向到一个新网站,tab1重定向到tab1.html,tab2重定向到tab2.html等等 我的问题是: 如果有3个选项卡处于“活动”状态,则它们应保持活动状态,即使我切换页面,也应显示它们。我应该能够在所有页面中看到相同的选项卡栏 每个选项卡都需要重定向到新网站。我不完全确定如何在这段代码中放置一个变量,以使链接动态变化 有几种方法可以让您在网站页面之间持久保存数据和/或状态,包括: Co
有几种方法可以让您在网站页面之间持久保存数据和/或状态,包括:
- Cookie(老式的,可以在客户端或服务器端读取)
- 查询字符串(URL末尾的
后跟?
键和
值)
- 散列片段(一个
后跟URL末尾的字符串)#
(包括两种变体:WebStorage
和localStorage
)sessionStorage
根据您上面描述的设置,您可以让
localStorage
中的每个键值条目描述一个选项卡和一个URL:
'Tab1' | '/tab1.html'
'Tab2' | '/tab2.html'
'Tab4' | '/tab4.html'
这意味着当用户单击选项卡1时:
// Grab tab1Button in DOM
const tab1Button = document.getElementById('tab1Button');
// Reusable function to create tabs
function createTab() {
// OTHER CODE
localStorage.setItem('Tab1', '/tab1.html');
}
// Event Listener which activates function when user clicks corresponding button
tab1Button.addEventListener('click', createTab, false);
然后,在页面加载时,Javascript将能够查询localStorage
,如下所示:
const myBar = document.getElementById('bar');
// Check 'Tab1' Entry exists
if (localStorage.get('Tab1') !== null) {
// Create Tab
const tab1Div = document.createElement('div');
tab1Div.id = 'tab1Div';
// Create Tab Link
const tab1Link = document.createElement('a');
tab1Link.setAttribute('href', localStorage.get('Tab1'));
tab1Link.textContent = 'Redirect';
// Add Tab Link to Tab
tab1Div.appendChild(tab1Link);
// Add Tab to DOM
myBar.appendChild(tab1Div);
}
进一步阅读:
- 按MDN
const myBar = document.getElementById('bar');
// Check 'Tab1' Entry exists
if (localStorage.get('Tab1') !== null) {
// Create Tab
const tab1Div = document.createElement('div');
tab1Div.id = 'tab1Div';
// Create Tab Link
const tab1Link = document.createElement('a');
tab1Link.setAttribute('href', localStorage.get('Tab1'));
tab1Link.textContent = 'Redirect';
// Add Tab Link to Tab
tab1Div.appendChild(tab1Link);
// Add Tab to DOM
myBar.appendChild(tab1Div);
}