在JavaScript中,实现跨页面的变量声明和共享通常有以下几种方式:
// 设置数据
localStorage.setItem('username', 'JohnDoe');
// 获取数据
const username = localStorage.getItem('username');
console.log(username); // 输出: JohnDoe
// 删除数据
localStorage.removeItem('username');
// 设置Cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
// 获取Cookie
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
const username = getCookie('username');
console.log(username); // 输出: JohnDoe
// 删除Cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
// 设置URL参数
const url = new URL('https://example.com/page');
url.searchParams.append('username', 'JohnDoe');
window.location.href = url.toString();
// 获取URL参数
const params = new URLSearchParams(window.location.search);
const username = params.get('username');
console.log(username); // 输出: JohnDoe
通过以上方法,可以在不同页面间实现变量的声明和共享,根据具体需求选择合适的方式。
领取专属 10元无门槛券
手把手带您无忧上云