对于纯Javascript,最简单的是:
document.onkeypress = function (e) {
e = e || window.event;
// use e.keyCode
};
But with this, you can only bind one handler for the event.
此外,您还可以使用以下内容将多个处理程序潜在地绑定到同一事件:
addEvent(document, "keypress", function (e) {
e = e || window.event;
// use e.keyCode
});
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}
在这两种情况下,keyCode
在不同浏览器中并不一致,因此还有更多需要判断和解决的问题.注意e = e || window.event
——这是Internet Explorer的一个正常问题,将事件放入window.event
,而不是将其传递给回调.
参考资料:
使用jQuery:
$(document).on("keypress", function (e) {
// use e.which
});
参考:
除了jQuery是一个"大型"库之外,jQuery还可以帮助解决浏览器之间的不一致性,尤其是窗口事件...这是不可否认的.希望很明显,我为您的示例提供的jQuery代码更优雅、更短,但却以一致的方式实现了您想要的.您应该能够相信e
(事件)和e.which
(按键代码,用于知道按下了哪个键)是准确的.在纯Javascript中,除非您执行jQuery库内部执行的所有操作,否则要知道这一点就有点困难.
Note there is a keydown
event, that is different than keypress
. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown
As for suggesting what to use, I would definitely suggest using jQuery if you're up for learning the framework. At the same time, I would say that you should learn Javascript's syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what's happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it's Javascript, and wraps the language.
jQuery非常有用的另一个例子是AJAX.浏览器与AJAX请求的处理方式不一致,因此jQuery会对其进行抽象,因此您不必担心.
这里有一些东西可能会帮助你做出决定: