[英]jquery - add event handler on event that takes another event as argument
I am trying to call a function scheduleAdd when the enter button is hit, but I only want it to work if an input with the id 'addSchedule' is in focus. 我试图在按下回车按钮时调用函数scheduleAdd,但是我只希望它在ID为'addSchedule'的输入中处于焦点时起作用。 Here's what I have: 这是我所拥有的:
$('#addSchedule').focus(function(e) {
var evt = e || window.event;
if(evt.keyCode == 13) {scheduleAdd};
});
I know the code inside the .focus works, because I tried it on its own and it triggers the function scheduleAdd when the enter key is hit. 我知道.focus内部的代码有效,因为我自己尝试了它,并且在按下Enter键时会触发函数scheduleAdd。 How can I make this conditional on 'addSchedule' being in focus? 如何以“ addSchedule”为关注焦点呢?
Also, more generally, I was wondering if there's a standard way to ascribe event handlers conditional on a second event, such as nesting .on() or something. 而且,更笼统地说,我想知道是否存在一种标准的方法来将事件处理程序归于第二个事件,例如嵌套.on()之类的东西。
Thanks. 谢谢。
Simply the keydown
event, and decide to do something or nothing based on whether the current element has the specified id: 只需keydown
事件,然后根据当前元素是否具有指定的ID来决定什么都不做:
$(document).on("keydown", function() {
if (!$("#addSchedule").is(":focus")) return;
// do stuff
});
Alternatively you can also check for the identity of the focused element with document.activeElement.id === "addSchedule"
if you don't mind that's not enough jQuery. 另外,如果您不介意jQuery不够用,还可以使用document.activeElement.id === "addSchedule"
检查焦点元素的身份。 ;-) ;-)
HTML: HTML:
<form>
<input id="addSchedule" type="text" />
</form>
Javascript: Javascript:
$('#addSchedule').keydown(function (event) {
if (event.which == 13) {
event.preventDefault(); // This will prevent the page refresh.
scheduleAdd();
}
function scheduleAdd() {
alert("Add the schedule");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.