.addEventListener enquiry
.addEventListener enquiry
本文关键字:enquiry addEventListener 更新时间:2023-09-26
所以这有效:
$('#divID').addEventListener('click', function() {alert('hi');}, false);
但是我试图让它工作,但就是不能
$('#divID').addEventListener('keypress', function(e) {
e = event || window.event;
if (e.keyCode == 40) {
//do something when the down arrow key is pressed.
}
}, false);
请帮忙,非常感谢。
我试图控制按下向下箭头键时会发生什么,但它仅适用于该特定的divID,而不是整个文档。
KeyPress
事件仅针对字符(可打印)键调用,KeyDown
事件针对所有(包括不可打印)键引发。
此外,行为因浏览器而异。
你已经把你的问题标记为jquery
,所以我假设你实际上正在使用它。
那里有几个问题:
-
keypress
仅针对可打印字符触发。对于箭头键,您需要keydown
(通常)或keyup
(很少)。 -
jQuery 实例没有
addEventListener
方法。你想要on
.(或者,您可以为要使用的事件使用特定于事件的别名。 -
jQuery
on
方法没有第三个参数。 -
jQuery 为您处理事件参数由某些处理程序机制传递而不是由其他处理程序机制传递的问题。它总是给你论据。
-
有些浏览器使用
keyCode
,有些浏览器使用which
.jQuery为您标准化为which
。
所以:
$('#divID').on('keydown', function(e) {
if (e.which == 40) {
//do something when the down arrow key is pressed.
}
});
更多: on
, 事件对象
要使div
接收按键,至少在某些浏览器上,它需要是或具有交互式内容(例如,它需要有一个input
,或者contenteditable
,或类似)。
带有contenteditable
div
的现场示例
$('#divID').on('keydown', function(e) {
if (e.which == 40) {
//do something when the down arrow key is pressed.
$("<p>").text("down arrow").appendTo(document.body);
return false;
}
});
<div id="divID" contenteditable>Click here to ensure the div has focus, then press the down arrow</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
或者,捕获document.body
(或document
)上的键下事件:
带有document.body
的实时示例:
$(document.body).on('keydown', function(e) {
if (e.which == 40) {
//do something when the down arrow key is pressed.
$("<p>").text("down arrow").appendTo(document.body);
return false;
}
});
<div id="divID">Click here to ensure the document has focus, then press the down arrow</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>