在JavaScript中,接收另一个页面的值可以通过多种方式实现,以下是一些常见的方法:
通过URL传递参数是最简单的方式之一。
发送页面(pageA.html):
<!DOCTYPE html>
<html>
<head>
<title>Page A</title>
</head>
<body>
<a href="pageB.html?value=Hello">Go to Page B</a>
</body>
</html>
接收页面(pageB.html):
<!DOCTYPE html>
<html>
<head>
<title>Page B</title>
<script>
window.onload = function() {
const urlParams = new URLSearchParams(window.location.search);
const value = urlParams.get('value');
console.log(value); // 输出: Hello
};
</script>
</head>
<body>
<p>Value from Page A: <span id="value"></span></p>
<script>
document.getElementById('value').innerText = urlParams.get('value');
</script>
</body>
</html>
LocalStorage允许你在浏览器中存储数据,这些数据可以在不同页面间共享。
发送页面(pageA.html):
<!DOCTYPE html>
<html>
<head>
<title>Page A</title>
</head>
<body>
<button onclick="sendValue()">Send Value</button>
<script>
function sendValue() {
localStorage.setItem('value', 'Hello');
window.location.href = 'pageB.html';
}
</script>
</body>
</html>
接收页面(pageB.html):
<!DOCTYPE html>
<html>
<head>
<title>Page B</title>
</head>
<body>
<p>Value from Page A: <span id="value"></span></p>
<script>
window.onload = function() {
const value = localStorage.getItem('value');
console.log(value); // 输出: Hello
document.getElementById('value').innerText = value;
localStorage.removeItem('value'); // 清除存储的数据
};
</script>
</body>
</html>
Cookie也可以用来在不同页面间传递数据。
发送页面(pageA.html):
<!DOCTYPE html>
<html>
<head>
<title>Page A</title>
</head>
<body>
<button onclick="sendValue()">Send Value</button>
<script>
function sendValue() {
document.cookie = "value=Hello; path=/";
window.location.href = 'pageB.html';
}
</script>
</body>
</html>
接收页面(pageB.html):
<!DOCTYPE html>
<html>
<head>
<title>Page B</title>
</head>
<body>
<p>Value from Page A: <span id="value"></span></p>
<script>
window.onload = function() {
const cookies = document.cookie.split(';').map(cookie => cookie.trim());
for (let cookie of cookies) {
if (cookie.startsWith("value=")) {
const value = cookie.substring(6);
console.log(value); // 输出: Hello
document.getElementById('value').innerText = value;
document.cookie = "value=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; // 清除cookie
break;
}
}
};
</script>
</body>
</html>
如果两个页面在同一个应用中,可以通过服务器端传递数据。
发送页面(pageA.html):
<!DOCTYPE html>
<html>
<head>
<title>Page A</title>
</head>
<body>
<form action="pageB.html" method="get">
<input type="hidden" name="value" value="Hello">
<button type="submit">Go to Page B</button>
</form>
</body>
</html>
接收页面(pageB.html):
<!DOCTYPE html>
<html>
<head>
<title>Page B</title>
</head>
<body>
<p>Value from Page A: <span id="value"></span></p>
<script>
window.onload = function() {
const urlParams = new URLSearchParams(window.location.search);
const value = urlParams.get('value');
console.log(value); // 输出: Hello
document.getElementById('value').innerText = value;
};
</script>
</body>
</html>
选择哪种方式取决于具体的应用场景和需求。
没有搜到相关的文章