如何通过JavaScript为IE键入输入框 [英] How to type on an input box via JavaScript for IE
本文介绍了如何通过JavaScript为IE键入输入框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图弄清楚如何在IE8和9的输入框上键入(通过事件未设置值)。我查看了网络上的一些示例 - 但无法使它们起作用。 (我不想依赖其他库的JQuery)
Trying to figure out how to type (via events not set the value) on an input box for IE8 and 9. I looked at some of the examples on the web - but couldnt get any of they to work. (I don't want to rely on JQuery of other libraries)
这是我到目前为止所拥有的:
Here is what I have so far:
<form>
<input type="text" id="txtfld" />
<input type="button" onclick="typeKey()" />
</form>
<script>
function typeKey(){
var txtField = document.getElementById('txtfld');
var evt= document.createEventObject();
evt.keyCode=68;
txtField.fireEvent('onkeypress', evt);
}
</script>
它不起作用,也不会出错。
It does not work, and it does not give an error either.
推荐答案
尝试此函数, fire(document.getElementById('txtfld'),'keypress',68)
:
function fire(el,evttype,code) {
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent( evttype, false, false);
evt.charCode= evt.keyCode = code;
el.dispatchEvent(evt);
} else if (document.createEventObject) {
var evt = document.createEventObject();
evt.charCode= evt.keyCode = code;
el.fireEvent('on' + evttype, evt);
}
}
祝你好运:)
这篇关于如何通过JavaScript为IE键入输入框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文