jQuery 当输入值以编程方式更改时触发更改事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16250464/
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
Trigger Change event when the Input value changed programmatically?
提问by Subin Jacob
I have an Input in my form.
我的表单中有一个输入。
<input type="text" id="changeProgramatic" onchange="return ChangeValue(this);"/>
If I change the value in this textBox (changeProgramatic) using another JavaScript function it won't trigger the change Event.(Note: I'm passing 'this' into the method)
如果我使用另一个 JavaScript 函数更改此 textBox (changeProgramatic) 中的值,则不会触发更改事件。(注意:我将“this”传递到方法中)
采纳答案by kayz1
You are using jQuery, right? Separate JavaScript from HTML.
您正在使用 jQuery,对吗?将 JavaScript 与 HTML 分开。
You can use triggeror triggerHandler.
您可以使用trigger或triggerHandler。
var $myInput = $('#changeProgramatic').on('change', ChangeValue);
var anotherFunction = function() {
$myInput.val('Another value');
$myInput.trigger('change');
};
回答by Nux
Vanilla JS solution:
香草JS解决方案:
var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));
Note that dispatchEvent
doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).
请注意,dispatchEvent
这在旧 IE 中不起作用(请参阅:caniuse)。所以你应该只在内部网站上使用它(而不是在拥有广泛受众的网站上).
So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional commentsto warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for:
typeof document.body.dispatchEvent === 'function'
.
因此,截至 2019 年,您可能只想确保您的客户/观众不使用 Windows XP(是的,有些人在 2019 年仍在使用)。您可能希望使用条件注释来警告客户您不支持旧版 IE(在本例中为 IE 11 之前),但请注意,条件注释仅在 IE9 之前有效(在 IE10 中无效)。所以你可能想改用特征检测。例如,您可以提前检查:
typeof document.body.dispatchEvent === 'function'
。
回答by Lahiru Chandima
If someone is using react, following will be useful:
如果有人正在使用 react,以下内容会很有用:
https://stackoverflow.com/a/62111884/1015678
https://stackoverflow.com/a/62111884/1015678
If you are using react, following will work:
如果您使用的是反应,以下将起作用:
const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));