我有一个我正在制作的网站的登录页面,当您输入名称并单击“提交”时,它会转到下一页并显示欢迎(输入名称)但我似乎无法在上面输入任何其他文字页面,有帮助吗?
index.html
<html>
<head>
<title>Test</title>
<script type="text/javascript">
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into localStorage
localStorage.setItem("mytext", mytext);
return true;
}
</script>
<link href="stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onSubmit="tosubmit();" action="home.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
home.html
<html>
<head>
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var mytext = localStorage.getItem("mytext");
// Writing the value in the document
document.write("Welcome "+mytext+"!");
}
</script>
<link href="stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body onLoad="init();">
<div id="container">
<div id="header">
</div>
<div id="navigation">
</div>
<div id="body">
</div>
<div id="rightcolumn">
</div>
<div id="footer">
Department of Computing
</div>
</div>
</body>
</html>
例如,在页脚中,“计算部门”没有出现
最佳答案
文档加载完成后,您将无法使用 document.write()
。如果您这样做,浏览器将打开一个新文档来替换当前文档,这就是您的页脚文本未显示在输出中的原因 (home.html
)。
使用 innerHTML 属性将 HTML 代码放入元素中
因此,在您的 home.html 中将 document.write()
更改为
document.getElementById("body").innerHTML="Welcome "+mytext+"!"; // here body name is the ID of element where you want to display your message.
这里更新了home.html
<html>
<head>
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var mytext = localStorage.getItem("mytext");
// Writing the value in the document
document.getElementById("body").innerHTML="Welcome "+mytext+"!"; // <-- this will display message in a element with id "body"
}
</script>
<link href="stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body onLoad="init();">
<div id="container">
<div id="header">
</div>
<div id="navigation">
</div>
<div id="body"> <!-- message will be shown here -->
</div>
<div id="rightcolumn">
</div>
<div id="footer">
Department of Computing
</div>
</div>
</body>
</html>
关于Javascript 提交表单并在另一个页面中显示消息。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23249028/