Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

javascript - 如何在没有jQuery的情况下以编程方式触发“输入”事件?(How do I programmatically trigger an “input” event without jQuery?)

I installed an event handler on an input using(我使用以下命令在input上安装了事件处理程序)

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 input event so that my event listener is called?(如何模拟input事件,以便调用事件侦听器?)   ask by bdesham translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...