Sub*_*cob 42 html javascript jquery
我的表单中有一个输入法.
<input type="text" id="changeProgramatic" onchange="return ChangeValue(this);"/>
如果我使用另一个JavaScript函数更改此textBox(changeProgramatic)中的值,它将不会触发更改事件.(注意:我将'this'传递给方法)
Nux*_*Nux 90
香草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).
kay*_*yz1 18
你正在使用jQuery,对吧?将JavaScript与HTML分开.
您可以使用trigger或triggerHandler.
var $myInput = $('#changeProgramatic').on('change', ChangeValue);
var anotherFunction = function() {
  $myInput.val('Another value');
  $myInput.trigger('change');
};
ask*_*kov 11
以编程方式更改值时,需要调用input事件,而不是change事件。
注意:每次元素值更改时都会触发输入事件。这与更改事件不同,更改事件仅在提交值时触发,例如按 Enter 键、从选项列表中选择值等。
const el = document.getElementById('changeProgramatic');
el.value = 'New Value'
el.dispatchEvent(new Event('input', { 'bubbles': true }));
如果有人正在使用 react,以下内容会很有用:
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 }));
| 归档时间: | 
 | 
| 查看次数: | 75272 次 | 
| 最近记录: |