简体   繁体   English

如果在编程之前更改了值,则手动更改值不会触发onChange事件

[英]Manually changing value does not trigger onChange event if the value was changed before programmatically

We have an input type = "number" and we have set an onChange method. 我们有一个输入type = "number" ,我们设置了一个onChange方法。

The default value of the input is 0. 输入的默认值为0。

Then we change the value programatically to say, 10. 然后我们以编程方式将值更改为10。

Now we change the value manually to 0 again. 现在我们再次手动将值更改为0。

The onChange Method is not called on the manually made change. 在手动更改时不调用onChange方法。 I think that's because the event wasn't called when we changed their value programmatically to 10. So in a way the control thinks that the value still is 0. 我认为这是因为当我们以编程方式将其值更改为10时未调用事件。因此,在某种程度上,控件认为该值仍为0。

This happens only when I set manually the value to the value it was having BEFORE the programmatic change. 只有当我手动将值设置为程序更改之前的值时,才会发生这种情况。 If I use any other value to make the manual change, the onChange event is triggered correctly. 如果我使用任何其他值来进行手动更改,则会正确触发onChange事件。

Programatically changing a form control's value doesn't trigger its change handler, probably because the change event was specified as occuring after the user had changed the value and the control lost focus. 以编程方式更改表单控件的值不会触发其更改处理程序,可能是因为更改事件被指定为在用户更改值并且控件失去焦点后发生。 Programmatic changes didn't follow that sequence (programmatically setting focus and blur to imitate user actions didn't help, though a programmatic change event could be dispatched on the element). 程序化更改不遵循该顺序(以编程方式设置焦点和模糊以模仿用户操作没有帮助,尽管可以在元素上分派程序化更改事件)。

HTML5 introduced a new input event that fires whenever an input receives user input: HTML5引入了一个新的输入事件,只要输入接收到用户输入,就会触发该事件:

<input id="i0" oninput="alert(this.value);" value="">

You could use that instead of onchange, but it fires on each keypress and also if text is pasted or dragged to the input. 您可以使用它而不是onchange,但它会在每个按键上触发,也可以将文本粘贴或拖动到输入。

Note however that no browser fully supports HTML5 (and probably never will, since it's a moving target), so you will need to provide feature testing and a fall back mechanism should the input event not be supported. 但请注意,没有浏览器完全支持HTML5(并且可能永远不会,因为它是移动目标),因此如果不支持输入事件,您将需要提供功能测试和回退机制。

The input needs focus for onchange to be triggered. 输入需要关注onchange以被触发。 That is actually a good thing if programatically setting the input value does not trigger the onchange event. 如果以编程方式设置输入值不会触发onchange事件,这实际上是一件好事。 It would have created a circular setting from between the input and the code. 它会在输入和代码之间创建一个循环设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM