[英]html button disappears after onclick() event
大家好,我是javascript的新手,我想知道為什么html按鈕在我單擊后就消失了。 瀏覽器顯示文本,但按鈕消失。 這是我的HTML看起來像
<html>
<head>
<script type="text/javascript">
function funcname(){
document.write("<br/> <br/> <br/> some text");
}
</script>
</head>
<body>
<form>
<input type="button" name="something" value="touch me" onclick="funcname()">
</form>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function funcname()
{
document.body.innerHTML += "Some Text";
}
</script>
</head>
<body>
<form>
<input type="button" name="something" value="touch me" onclick="funcname()">
</form>
</body>
</html>
嘗試上面的代碼可以正常工作。如果使用document.write()覆蓋主體,則應使用document.body.innerHTML。
如Mozilla開發人員網絡所述,Document.write函數在調用時會覆蓋文檔內容:
注意:當document.write寫入文檔流時,在關閉的(加載的)文檔上調用document.write會自動調用document.open,這將清除文檔。
來源: https : //developer.mozilla.org/en-US/docs/Web/API/Document/write
document.write()
將覆蓋您的整個body
元素。 如果只想覆蓋特定的部分,則可以定義一個目標並使用innerHTML
更改文本。
<html>
<head>
<script type="text/javascript">
function funcname(){
document.getElementById("someParagraph").innerHTML = "Paragraph changed!";
}
</script>
</head>
<body>
<form>
<input type="button" name="something" value="touch me" onclick="funcname()">
</form>
<p id="someParagraph">Hey<p>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.