我是js新手。
我正在尝试获取 textbox
的值并显示在新页面中。
但不知何故,当我单击按钮时,它会显示一秒钟的值,然后重定向到同一表单页面。
请告诉我我哪里做错了?谢谢。
这是我的代码
HTML
<div id="myDiv">
<strong>Enter your name in the box below, then click
the button to see a personalized page!</strong>
<br>
<form id="newp" onsubmit="newpage();">
Name: <input type="text" id="yourname" size="25">
<br><br>
<input type="submit" onclick="pressedbutton()" value="Submit">
</form>
<script type="text/javascript" src="main.js"></script>
</div>
JS
function pressedbutton()
{
var thename = document.getElementById("yourname").value;
document.open();
document.write("<h1>Welcome!</h1>");
document.write("Hello, " + thename + ", and welcome to my page!");
document.close();
}
谢谢。
最佳答案
当您在已加载的文档上调用 document.open()
然后调用 document.write()
时,它将清除当前文档并用新文档替换它空文档。
如果您只想向当前文档添加一些内容,那么您应该使用 DOM 操作。创建新元素并将它们添加到当前文档。
例如,您可以这样做:
function pressedbutton() {
var thename = document.getElementById("yourname").value;
var div = document.createElement("div");
div.innerHTML = "<h1>Welcome!</h1>Hello, " + thename + ", and welcome to my page!";
document.body.appendChild(div);
// prevent form submission
return false;
}
<小时/>
此外,您的表单正在提交回服务器,这会导致页面重新加载。您可以通过将按钮更改为常规按钮而不是提交按钮或阻止提交按钮的默认行为来防止这种情况。
如果您不打算提交表单,只需更改按钮即可:
<input type="submit" onclick="pressedbutton()" value="Submit">
对此:
<input type="button" onclick="pressedbutton()" value="Submit">
关于javascript open() 方法冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147256/