Javascript:在 onkeyup 事件中更改值时不会触发 onchange 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15036965/
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
Javascript : onchange event does not fire when value is changed in onkeyup event
提问by hieund
I have this simply code :
我有这个简单的代码:
<body>
<input type="text" onkeyup="this.value = (new Date()).getSeconds()" onchange="alert(1)" />
</body>
I dont't know why the textbox value has changed when i press the key but the onchange event does not fire. How can i fire onchange event ?
我不知道为什么当我按下键时文本框的值发生了变化,但 onchange 事件没有触发。我怎样才能触发 onchange 事件?
采纳答案by martriay
The onchange
will fire when you leave the focus from it (if you performed any changes). This behavior occurs only with text
and textarea
input types because javascript doesn't know when you're done typing.
onchange
当您离开它时(如果您进行了任何更改),它将触发。此行为仅在输入类型text
和textarea
输入类型时发生,因为 javascript 不知道您何时完成输入。
I don't know why there is a checkbox in the code, but whatever. Sincerely, I'm not being able to tell you why, but the problem is the dynamic value change on the input (a guess would be that the change isn't performed by the user, but I really don't know), if you remove the code inside the onkeyup it will work. Whatever, if what you want is to execute some code when the input loses focus, you can use onblur
instead, is more accurate in that case.
我不知道为什么代码中有一个复选框,但无论如何。真诚地,我无法告诉您原因,但问题是输入的动态值更改(猜测是更改不是由用户执行的,但我真的不知道),如果您删除 onkeyup 中的代码它将起作用。无论如何,如果您想要在输入失去焦点时执行一些代码,您可以onblur
改用,在这种情况下更准确。