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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35659430/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:05:16  来源:igfitidea点击:

How do I programmatically trigger an “input” event without jQuery?

javascript

提问by bdesham

I installed an event handler on an inputusing

我在inputusing上安装了一个事件处理程序

var element = document.getElementById('some-input');
element.addEventListener('input', function() {
    console.log('The value is now ' + element.value);
});

As expected, the handler is triggered when I type into the text field, but I also need to invoke this handler from my code. How can I simulate the inputevent so that my event listener is called?

正如预期的那样,当我在文本字段中键入时会触发处理程序,但我还需要从我的代码中调用此处理程序。如何模拟input事件以便调用我的事件侦听器?

回答by adeneo

The proper way to trigger an event with plain JavaScript, would be to create an Event object, and dispatch it

使用纯 JavaScript 触发事件的正确方法是创建一个 Event 对象,然后调度它

var event = new Event('input', {
    bubbles: true,
    cancelable: true,
});

element.dispatchEvent(event);

FIDDLE

小提琴

This is not supported in IE, for that the old-fashioned way still has to be used

IE 不支持这个,因为老式的方式仍然必须使用

var event = document.createEvent('Event');
event.initEvent('input', true, true);

elem.dispatchEvent(event);

回答by Lahiru Chandima

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 }));

回答by Antare74

Try this code

试试这个代码

var event = document.createEvent('Event');
event.initEvent('input', true, true);

elem.dispatchEvent(event);