onKeyUp 不工作 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24191313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
onKeyUp not working javascript
提问by Dino
I am trying to populate the div tag with what is typed in the name field (example below) using javascript. I am not sure what I am doing wrong but it is not working and I have at a loss as to why not? All I want is when the user types their first name it appears below. I have looked at other examples and still confused why this one will not work.
我正在尝试使用 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>
回答by epascarello
You are referencing the element before it is rendered. It is like trying to eat a pizza before you make it.
您在呈现元素之前引用该元素。这就像在做披萨之前试图吃掉它。
You need to attach the event after the element is rendered. Either window.onload, document ready, or add the script after the element in the markup.
您需要在元素呈现后附加事件。无论是在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>