如何在 IE8 中生成具有特定键码的 keyup 事件?
我需要使用本机 DOM 函数(无 jQuery)在 IE 8 中生成 keyup 事件。以下代码生成、触发并接收事件,但 keyCode 始终为 0。如何正确传递 keyCode?
<form><input id="me" type="submit" /></form>
<script type="text/javascript">
var me = document.getElementById("me");
me.attachEvent("onkeyup", function(e) {
alert(e.keyCode); // => 0
});
document.getElementById("me").fireEvent('onkeyup', 13);
</script>
I need to generate keyup events in IE 8 using native DOM functions (no jQuery). The following code generates, fires, and receives the event, but the keyCode is always 0. How do I properly pass the keyCode?
<form><input id="me" type="submit" /></form>
<script type="text/javascript">
var me = document.getElementById("me");
me.attachEvent("onkeyup", function(e) {
alert(e.keyCode); // => 0
});
document.getElementById("me").fireEvent('onkeyup', 13);
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
想通了。解决方案是创建一个事件对象,分配键码,然后从节点触发它。
Figured it out. The solution is to create an event object, assign the keycode, and fire it from the node.
这将使事件在所有浏览器中工作。
另外,我更喜欢使用
me.onkeyup = function(e) { ... }
,但这只是个人喜好(我知道这种方法的缺点,但我有聪明的方法来解决他们)That will make events work in all browsers.
Also, I prefer to use
me.onkeyup = function(e) { ... }
, but that' just personal preference (I know the drawbacks of this method, but I have clever ways to work around them)