onKeyUp不工作的JavaScript

Din*_*ino 1 html javascript

我试图使用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> 
Run Code Online (Sandbox Code Playgroud)

epa*_*llo 9

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

您需要在呈现元素后附加事件.无论是在window.onload,文件准备,或在标记元素后添加脚本.

<!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> 
Run Code Online (Sandbox Code Playgroud)

  • 比萨示例总是 +1 (2认同)