在事件处理程序中使用document.write? [英] Using document.write in event handler?

查看:92
本文介绍了在事件处理程序中使用document.write?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验HTML和JavaScript。在文本框中输入按键时,下面的代码应该会打印一些内容:

 < html> 
< body>
< input type =textid =commandInputname =commandsize =50/>
< script type =text / javascript>
var commandInput = document.getElementById(commandInput);
commandInput.onkeydown = function(evt){
document.writeln(Test);
};
< / script>

< / body>
< / html>

出于某种原因,输入按键时文本框消失,只剩下白色页面。 >

任何想法为什么会发生这种情况?

解决方案

code> document.write 或 document.writeln 。在页面加载后调用它(至少在Firefox中)会自动调用 document.open(),这将清除当前文档。



如果你使用它作为调试工具,我建议使用Firebug和 console.log()来代替。 p>

I am experimenting with HTML and JavaScript. The following code should print something when entering a keystroke in a textbox:

<html>
    <body>
        <input type="text" id="commandInput" name="command" size="50" />
        <script type="text/javascript">
            var commandInput = document.getElementById("commandInput");
            commandInput.onkeydown = function (evt) {
                document.writeln("Test");
            };
        </script>    

    </body>
</html>

For some reason the textbox disappears when entering a keystroke, leaving nothing but a white page.

Any ideas why this is happening?

解决方案

You shouldn't use document.write or document.writeln after the page has loaded. Calling it after the page has loaded (in Firefox, at least) does an automatic call to document.open(), which wipes out the current document.

If you're using it as a debugging tool, I'd suggest using Firebug and console.log() instead.

这篇关于在事件处理程序中使用document.write?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆