请问document.write清除页面

document.write清除页面

为什么在下面的代码中,document.write在函数调用时,validator()表单元素(复选框和按钮)将从屏幕中删除?

<!DOCTYPE html><html>
    <head>
        <script type="text/javascript">
            function validator() {
                if (document.myForm.thebox.checked)
                    document.write("checkBox is checked");
                else 
                    document.write("checkBox is NOT checked");
            }
        </script>
    </head>
    <body>
        <form name="myForm">
            <input type="checkbox" name ="thebox"/>
            <input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
        </form>
    </body></html>


心有法竹
浏览 463回答 3
3回答

ABOUTYOU

document.write()用于写入文档流。在您的情况下,当调用onClick处理程序时,流很可能已经关闭,因为您的文档已完成加载。调用document.write()已关闭的文档流会自动调用document.open(),这将清除文档。

RISEBY

一个document.write()页面加载后调用将覆盖当前文档。您想要在文档中设置某些元素的文本。如果你添加一个<p&nbsp;id="message"></p>到你身体的尽头,然后你可以打电话document.getElementById("message").innerHTML&nbsp;=&nbsp;"your&nbsp;text&nbsp;here";或者使用jQuery库$("#message").html("your&nbsp;text&nbsp;here");
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript