![](/img/trans.png)
[英]Passing Variable through JavaScript from one html page to another page
[英]Passing javascript variable from one html page to another page
您好,我最近开始从事html的工作,但是在这种情况下,我感到震惊,我想将值从一个html页面发送到下一个html页面,就像网站注册成功后如何显示我们的名字一样。在这里,我写了两个html的网页,
pageOne.html
<!DOCTYPE html>
<head>
<title>
Home
</title>
<meta charset="UTF-8">
</head>
<style>
.myP{
color: lightgreen;}
</style>
<body>
<p id="p1" class="myP" onclick="myFun()">DataSend</p>
</body>
<script>
function myFun(){
document.getElementById("p1").style.color = "blue";
var textprevi=document.getElementById("p1").innerHTML;
localStorage.setItem("message", textprevi);
window.open("pageTwo.html","_self");
}
</script>
</html>
还有我的第二个
pageTwo.html
<!DOCTYPE html>
<html>
<body onload="fun">
<input type="text" id="tBox">
</body>
<script>
function fun()
{
document.getElementById("tBox").innerHTML = localStorage.getItem("message");
}
</script>
</html>
但是,当我尝试上述解决方案时,id =“ tBox ”的元素为空,但我希望它填充来自pageOne.html的value =“ DataSend”。 请帮助我解决这个问题。 提前致谢。
问题是这条线
document.getElementById("tBox").innerHTML = localStorage.getItem("message");
这里tBox
是一个输入元素。 因此,您必须使用value
而不是innerHTML
document.getElementById("tBox").value= localStorage.getItem("message");
您可以使用querystring参数做到这一点在第一页中:
function myFun(){
document.getElementById("p1").style.color = "blue";
var textprevi=document.getElementById("p1").innerHTML;
window.open("pageTwo.html?data=" + textprevi,"_self");
}
在第2页
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var data = getParameterByName('data');
您在pageTwo.html中犯了两个错误。
<!DOCTYPE html>
<html>
<body onload="fun()"><!-- You didn't invoke the function here -->
<input type="text" id="tBox">
</body>
<script>
function fun()
{
document.getElementById("tBox").value = localStorage.getItem("message"); // You need to set the value for input fields, not innerHTML.
}
</script>
</html>
这些更改将使您的代码正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.