如何在没有jQuery的情况下以编程方式触发"输入"事件?

bde*_*ham 38 javascript

我在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)

  • 这与 new InputEvent() 有什么区别?什么时候应该使用 InputEvent? (7认同)
  • 现代复制粘贴:`element.dispatchEvent(new Event('input',{bubble:true}))) (4认同)

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)


Lah*_*ima 5

如果您使用的是反应,以下将起作用:

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)