Javascript html文本输入onchange事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6169353/
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
html text input onchange event
提问by user775187
is there a way to implement a text change event to detect text change on an HTML input text field?
It's possible to simulate these using key events (key press etc), however, it's really not performant and difficult, is there a better way?
有没有办法实现文本更改事件来检测 HTML 输入文本字段上的文本更改?
可以使用按键事件(按键等)来模拟这些,但是,它确实没有性能和困难,有没有更好的方法?
回答by DragonLord
onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:
onChange 不会触发,直到您稍后失去焦点。如果您想对各种瞬时变化非常严格,请使用:
<input
type = "text"
onchange = "myHandler();"
onkeypress = "this.onchange();"
onpaste = "this.onchange();"
oninput = "this.onchange();"
/>
回答by CaffeinatedCM
When I'm doing something like this I use the onKeyUp event.
当我做这样的事情时,我使用 onKeyUp 事件。
<script type="text/javascript">
function bar() {
//do stuff
}
<input type="text" name="foo" onKeyUp="return bar()" />
but if you don't want to use an HTML event you could try to use jQuerys .change() method
但是如果你不想使用 HTML 事件,你可以尝试使用 jQuerys .change() 方法
$('.target').change(function() {
//do stuff
});
in this example, the input would have to have a class "target"
在这个例子中,输入必须有一个类“目标”
if you're going to have multiple text boxes that you want to have done the same thing when their text is changed and you need their data then you could do this:
如果您将有多个文本框,并且希望在更改文本时执行相同的操作并且需要它们的数据,那么您可以执行以下操作:
$('.target').change(function(event) {
//do stuff with the "event" object as the object that called the method
)};
that way you can use the same code, for multiple text boxes using the same class without having to rewrite any code.
这样您就可以对使用相同类的多个文本框使用相同的代码,而无需重写任何代码。
回答by Jonathon
Well unless I misunderstand you can just use the onChange
attribute:
好吧,除非我误解你可以只使用onChange
属性:
<input type="text" onChange="return bar()">
Note: in FF 3 (at least) this is not called until some the user has confirmed they are changed either by clicking away from the element, clicking enter, or other.
注意:在 FF 3(至少)中,直到某些用户通过单击远离元素、单击 Enter 或其他方式确认他们已更改时,才会调用此方法。
回答by Marco
I used this line to listen for input events from javascript.
It is useful because it listens for text change and text pasted events.
我用这一行来监听来自 javascript 的输入事件。
它很有用,因为它侦听文本更改和文本粘贴事件。
myElement.addEventListener('input', e => { myEvent() });