<分区>
我正在尝试用 JavaScript
做一些证明,但我看到一种行为,我认为它不必像这样。这是我的代码:
代码:
<!DOCTYPE html>
<head>
<meta charset = "utf-8"/>
<title> Exercise prompt </title>
<script type = "text/javascript">
function disp_prompt()
{
var name = prompt("Please enter your name", "");
if(name != null && name != "")
{
document.write("Hi " + name + " How are you?");
}
}
</script>
</head>
<body>
<input type = "button" onclick = "disp_prompt()" value = "Show a prompt box." />
</body>
</html>
预期结果:
当我点击按钮时,出现提示,当我点击“接受”按钮时,函数document.write
上的语句必须在按钮下方。
结果:
当 提示框
显示时,我按下“接受”按钮,按钮消失,它只显示函数 document.write
上的句子。
我可以在 w3schools 上看到以下句子:
Write some text directly to the HTML document
但我还可以看到另一个声明:
Using document.write() after an HTML document is fully loaded, will delete all existing HTML.
所以我无法理解document.write
的真正目的。如果您想在 HTML
上写一些文本...为什么必须删除其余元素?
是否有一种方法可以避免这种情况并将其余元素保留在 HTML
中?
提前致谢!