我在input使用上安装了一个事件处理程序
var element = document.getElementById('some-input');
element.addEventListener('input', function() {
console.log('The value is now ' + element.value);
});
Run Code Online (Sandbox Code Playgroud)
正如所料,当我在文本字段中键入时会触发处理程序,但我还需要从我的代码中调用此处理程序.如何模拟input事件以便调用我的事件监听器?
ade*_*neo 70
使用纯JavaScript触发事件的正确方法是创建一个Event对象,并将其分派
var event = new Event('input', {
bubbles: true,
cancelable: true,
});
element.dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)
在IE中不支持这种方式,因为仍然必须使用老式的方式
var event = document.createEvent('Event');
event.initEvent('input', true, true);
elem.dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)
Adm*_*ama 16
这个答案隐藏在评论中,但比最受欢迎的答案更简洁,所以我要试一试作为自己的答案。希望能帮助到你。
element.dispatchEvent(new Event('input', { bubbles: true }));
Run Code Online (Sandbox Code Playgroud)
或者甚至可能只是...
element.dispatchEvent(new Event('input'));
Run Code Online (Sandbox Code Playgroud)
如果您使用的是反应,以下将起作用:
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 }));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30826 次 |
| 最近记录: |