[英]Passing javascript variable from one html page to another page
Hello All i started working on html recently,but iam struck in this situation where i want to send a value from one html page to the next html page just like,how websites shows our name after sign up success.Here i have written two html pages with, 您好,我最近开始从事html的工作,但是在这种情况下,我感到震惊,我想将值从一个html页面发送到下一个html页面,就像网站注册成功后如何显示我们的名字一样。在这里,我写了两个html的网页,
pageOne.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>
and my second 还有我的第二个
pageTwo.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>
But when i tried the above solution,the element with id = " tBox " was empty but i wanted it to be filled with value = "DataSend" which is from pageOne.html. 但是,当我尝试上述解决方案时,id =“ tBox ”的元素为空,但我希望它填充来自pageOne.html的value =“ DataSend”。 Please help me with the promblem.
请帮助我解决这个问题。 Thanks in advance.
提前致谢。
The problem is with this line 问题是这条线
document.getElementById("tBox").innerHTML = localStorage.getItem("message");
Here tBox
is a an input element. 这里
tBox
是一个输入元素。 So you have to use value
instead of innerHTML
因此,您必须使用
value
而不是innerHTML
document.getElementById("tBox").value= localStorage.getItem("message");
You can do it using querystring parameters In page one: 您可以使用querystring参数做到这一点在第一页中:
function myFun(){
document.getElementById("p1").style.color = "blue";
var textprevi=document.getElementById("p1").innerHTML;
window.open("pageTwo.html?data=" + textprevi,"_self");
}
In page 2 在第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');
You made two mistakes in pageTwo.html. 您在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>
These changes should make your code work. 这些更改将使您的代码正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.