[英]onchange property doesn`t work in javascript
I want to launch the function test()
if the user inputs something in the html input field with the id="sc1dc1"
(without using the "onchange="
directly in HTML).如果用户在
id="sc1dc1"
的 html 输入字段中输入某些内容(不直接在 HTML 中使用"onchange="
test()
我想启动函数test()
)。 What is wrong?怎么了?
HTML: HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="text" id="sc1dc1" >
</body>
</html>
Javascript: Javascript:
var x = document.getElementById("sc1dc1").value;
x.onchange = test;
function test(){alert("Test")};
The thing about onchange
events is that they only fire when the <input>
field loses focus.关于
onchange
事件的事情是它们只在<input>
字段失去焦点时触发。 If you want an immediate response, you should use oninput
like so:如果您想要立即响应,您应该像这样使用
oninput
:
x.oninput = test;
You also need to make x
equal to the actual element , not the value of the element.您还需要使
x
等于实际元素,而不是元素的值。 Removing:删除:
.value
From this line:从这一行:
var x = document.getElementById("sc1dc1").value;
Will fix it.会修好。
Demonstration with onchange
:使用
onchange
演示:
var x = document.getElementById("sc1dc1"); x.onchange = test; function test() { alert("Test") };
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <input type="text" id="sc1dc1"> </body> </html>
Demonstration with oninput
:使用
oninput
演示:
var x = document.getElementById("sc1dc1"); x.oninput = test; function test() { alert("Test") };
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <input type="text" id="sc1dc1"> </body> </html>
The javascript should be this: javascript应该是这样的:
var x = document.getElementById("sc1dc1"); x.onchange = test; function test(){alert("Test")};
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <input type="text" id="sc1dc1" > </body> </html>
You don't need .value你不需要 .value
You need to assign the function test
to the element's oninput
attribute.您需要将功能
test
分配给元素的oninput
属性。 x
should be the HTMLInputElement
, not the value of the element. x
应该是HTMLInputElement
,而不是元素的值。
Change改变
var x = document.getElementById("sc1dc1").value;
To到
var x = document.getElementById("sc1dc1");
Use oninput
instead of onchange
if you want to trigger your event handler right when text is entered and not after the input loses focus.如果您想在输入文本
oninput
不是在输入失去焦点后立即触发事件处理程序,请使用oninput
而不是onchange
。
var x = document.getElementById("sc1dc1"); x.oninput = test; function test(){alert("Test")};
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <input type="text" id="sc1dc1" > </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.