在JavaScript中,将文本框内容传递到新页面可以通过多种方式实现。以下是几种常见的方法:
你可以将文本框的内容作为URL参数传递到新页面。
示例代码:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>传递文本框内容</title>
</head>
<body>
<input type="text" id="textInput" placeholder="输入一些文本">
<button onclick="navigateToNewPage()">跳转到新页面</button>
<script>
function navigateToNewPage() {
const textInput = document.getElementById('textInput').value;
window.location.href = `newpage.html?text=${encodeURIComponent(textInput)}`;
}
</script>
</body>
</html>
<!-- newpage.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新页面</title>
</head>
<body>
<h1>传递过来的文本内容是:</h1>
<p id="displayText"></p>
<script>
const urlParams = new URLSearchParams(window.location.search);
const text = urlParams.get('text');
document.getElementById('displayText').innerText = decodeURIComponent(text);
</script>
</body>
</html>
优势:
应用场景:
你可以将文本框的内容存储在浏览器的本地存储中,然后在新的页面中读取这些数据。
示例代码:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>传递文本框内容</title>
</head>
<body>
<input type="text" id="textInput" placeholder="输入一些文本">
<button onclick="saveAndNavigate()">跳转到新页面</button>
<script>
function saveAndNavigate() {
const textInput = document.getElementById('textInput').value;
localStorage.setItem('userText', textInput);
window.location.href = 'newpage.html';
}
</script>
</body>
</html>
<!-- newpage.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新页面</title>
</head>
<body>
<h1>传递过来的文本内容是:</h1>
<p id="displayText"></p>
<script>
const text = localStorage.getItem('userText');
document.getElementById('displayText').innerText = text;
</script>
</body>
</html>
优势:
应用场景:
类似于LocalStorage,但数据仅在当前会话期间有效。
示例代码:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>传递文本框内容</title>
</head>
<body>
<input type="text" id="textInput" placeholder="输入一些文本">
<button onclick="saveAndNavigate()">跳转到新页面</button>
<script>
function saveAndNavigate() {
const textInput = document.getElementById('textInput').value;
sessionStorage.setItem('userText', textInput);
window.location.href = 'newpage.html';
}
</script>
</body>
</html>
<!-- newpage.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新页面</title>
</head>
<body>
<h1>传递过来的文本内容是:</h1>
<p id="displayText"></p>
<script>
const text = sessionStorage.getItem('userText');
document.getElementById('displayText').innerText = text;
</script>
</body>
</html>
优势:
应用场景:
通过以上方法,你可以根据具体需求选择合适的方式来传递文本框内容到新页面。
领取专属 10元无门槛券
手把手带您无忧上云