开发者

Using document.write in event handler?

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.


Here is an alternative method, using .innerHTML to insert text in an element.

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


Try onkeyup, instead, so that it takes the most recent input into the new field.

On a sidenote, toss this into a new.html and check it out, may interest you if you're just fooling around, as it comes up with a pretty cool effect.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>onkeyup</title>
<script type="text/javascript">
    function setFocus(){
        document.theForm.command.focus();   
    }
</script>
</head>

<body onload="setFocus()">
<form id="theForm">
<input type="text" id="commandInput" name="command" size="50" style="font-size:20px; color:gray; font-family:arial; border:0 none; opacity:0.4" />
        <div id="text" style="position:absolute; float:left; margin-left:3px; margin-top:-26px; font-size:20px; font-family:arial; color:black;"></div>
        <script type="text/javascript">
            var commandInput = document.getElementById("commandInput");
            commandInput.onkeyup = function () {
                document.getElementById("text").innerHTML=commandInput.value;
            };
        </script>   
</form> 
</body>
</html>

When you load the page, hit Tab and start typing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜