如何在没有 jQuery 的情况下以编程方式触发“输入”事件
How do I programmatically trigger an “input” event without jQuery?
我在input
上安装了事件处理程序
var element = document.getElementById('some-input');
element.addEventListener('input', function() {
console.log('The value is now ' + element.value);
});
正如预期的那样,当我在文本字段中键入时会触发处理程序,但我还需要从我的代码中调用此处理程序。如何模拟input
事件以便调用事件侦听器?
创建一个事件对象,并调度它
var event = new Event('input', {
bubbles: true,
cancelable: true,
});
element.dispatchEvent(event);
或者,作为单行:
element.dispatchEvent(new Event('input', { bubbles: true }));
小提琴
这在IE中不受支持,因为必须使用老式的方式
var event = document.createEvent('Event');
event.initEvent('input', true, true);
elem.dispatchEvent(event);
element.dispatchEvent(new Event('input'));
如果您使用的是 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 }));
相关文章:
- 以编程方式填充组合框道场 (1.8) 的最佳方法是什么?
- 以编程方式选择文本Mobile Safari
- Thunderbird,如何以编程方式选择第一个选项卡
- 以编程方式获取无线接入点列表
- 使用Javascript/jQuery以编程方式将当前锚点/哈希/片段附加到任何表单操作url
- 通过javascript以编程方式将文件插入HTML输入
- 如何以非编程方式国际化HTML文本
- Y组合器如何以编程方式计算不动点
- 如何以编程方式添加到可变嵌套对象中
- 在视图中渲染多个按钮以编程方式进行本机反应
- 为什么我在以编程方式打开窗口时遇到问题
- 以编程方式添加的复选框的值
- 以编程方式将fabric-js-canvas的图像替换为hq图像,并重新计算其他对象的坐标和大小
- 可以't以编程方式关闭jQuery移动弹出窗口中的可折叠部分
- 以编程方式调用javascript函数
- 如何以编程方式查找javascript语法错误的位置
- 以编程方式将特定的JavaScript添加到Qualtrics中的特定问题中
- 当以编程方式更改输入值时,不会执行更改时事件
- 如何以编程方式在 jsTree 中选择一个节点并打开所有父节点
- 我如何以与使用@ configationproperties相同的方式以编程方式加载yaml文件