onKeyUp不工作的JavaScript

时间:2014-06-12 18:19:55

标签: javascript html

我正在尝试使用javascript填充div标签,其中包含名称字段中输入的内容(下面的示例)。我不确定我做错了什么,但它不起作用,我不知道为什么不呢? 我想要的只是当用户输入下面显示的名字时。我看过其他的例子,但仍然混淆了为什么这个例子不起作用。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4 /strict.dtd"> 
<html lang="en-GB"> 
  <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>hello whirled</title> 
    <script type="text/javascript">
        document.getElementById("name").onkeyup = function() {
            document.getElementById("display").innerHTML = this.value;
        }
    </script> 
</head> 
<body> 
    <h1> 
        Bla Bla
    </h1> 
    <form method="get" action=" "> 
        <p> 
            Other Text goes here
        </p> 
        <p> 
            Type your first name here: 
            <input type="text" id="name" value="">
        </p> 
        <div id="display">'s ball is not in the ball park.</div> 
        <noscript>  
            <div> 
                If you can see this then SCRIPTS are turned OFF on your machine and it won't work 
            </div>   
        </noscript> 
    </form> 
</body> 

1 个答案:

答案 0 :(得分:8)

您在呈现元素之前引用该元素。这就像在你做之前尝试吃披萨一样。

您需要在渲染元素后附加事件。 window.onloaddocument ready,或在标记中的元素后添加脚本。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4 /strict.dtd"> 
<html lang="en-GB"> 
  <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>hello whirled</title>      
</head> 
<body> 
    <h1> 
        Bla Bla
    </h1> 
    <form method="get" action=" "> 
        <p> 
            Other Text goes here
        </p> 
        <p> 
            Type your first name here: 
            <input type="text" id="name" value="">
        </p> 
        <div id="display">'s ball is not in the ball park.</div> 
        <noscript>  
            <div> 
                If you can see this then SCRIPTS are turned OFF on your machine and it won't work 
            </div>   
        </noscript> 
    </form>
    <script type="text/javascript">
        document.getElementById("name").onkeyup = function() {
            document.getElementById("display").innerHTML = this.value;
        }
    </script> 
  </body>
</html>