document.write清除页面

C g*_*ics 17 html javascript javascript-events

为什么在下面的代码中,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>
Run Code Online (Sandbox Code Playgroud)

Jer*_*NER 58

document.write()用于写入文档.

在您的情况下,当调用onClick处理程序时,流很可能已经关闭,因为您的文档已完成加载.

调用document.write()已关闭的文档流会自动调用document.open(),这将清除文档.

  • @JeromeWAGNER-不。阅读从您引用的页面链接的[*规格*](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-72161170):“ *为以下内容打开文档流如果目标中存在文档,则此方法将其清除。*“ (2认同)

And*_*nes 12

一个document.write()页面加载后调用将覆盖当前文档.

您想要在文档中设置某些元素的文本.如果你添加一个

<p id="message"></p>
Run Code Online (Sandbox Code Playgroud)

到你身体的尽头,然后你可以打电话

document.getElementById("message").innerHTML = "your text here";
Run Code Online (Sandbox Code Playgroud)

或者使用jQuery库

$("#message").html("your text here");
Run Code Online (Sandbox Code Playgroud)


jos*_*736 10

document.write 文档加载调用隐式调用document.open,这将清除当前文档.(document.open与页面加载时调用相比,将字符串插入文档流;它不会清除文档.)

document.write是古代JavaScript中最古老的遗迹之一,通常应该避免.相反,您可能希望使用DOM操作方法来更新文档.