74

我的表单中有一个输入。

<input type="text" id="changeProgramatic" onchange="return ChangeValue(this);"/>

如果我使用另一个 JavaScript 函数更改此文本框(changeProgramatic)中的值,则不会触发更改事件。(注意:我将“this”传递给方法)

4

3 回答 3

161

香草JS解决方案:

var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));

请注意,dispatchEvent这在旧 IE 中不起作用(请参阅:caniuse)。所以你应该只在内部网站上使用它(而不是在有广泛受众的网站上).

因此,从 2019 年开始,您可能只想确保您的客户/观众不使用 Windows XP(是的,有些人在 2019 年仍然使用)。您可能希望使用条件注释来警告客户您不支持旧 IE(在本例中为 IE 11 之前),但请注意,条件注释仅在 IE9 之前有效(在 IE10 中无效)。因此,您可能想改用特征检测。例如,您可以提前检查: typeof document.body.dispatchEvent === 'function'

于 2016-03-18T12:31:14.227 回答
33

您正在使用 jQuery,对吗?将 JavaScript 与 HTML 分开。

您可以使用triggertriggerHandler

var $myInput = $('#changeProgramatic').on('change', ChangeValue);

var anotherFunction = function() {
  $myInput.val('Another value');
  $myInput.trigger('change');
};
于 2013-04-27T09:40:31.427 回答
8

如果有人正在使用 react,以下内容将很有用:

https://stackoverflow.com/a/62111884/1015678

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 }));
于 2020-05-31T05:19:18.907 回答