使用 JQuery 取消绑定文本输入的自定义键事件



当按下 ENTER 键时,我将一个函数绑定到键下事件。我希望此函数在 ENTER 键下触发,除非用户在文本区域中键入 idinput_area

$(document).keydown(function(e) {
if (e.keyCode == 32 && e.target != $("#input_area")) {
scroll_to_location();
}
});

我试图用$(document).unbind('keydown')取消绑定整个键,但这对整个文档完全如此,而不仅仅是在有文本输入的短暂时间内。

有没有一种巧妙的方法可以使用 JQuery 取消绑定文本区域输入的事件?

您可以检查原始事件目标 ID 以查看它是否是应忽略的元素。

$(document).on('keydown', function (e) {
if (e.originalEvent.target.id === 'input_area') return;
//do logic
});

我建议像这样打开和关闭绑定/取消绑定:

$(document).on('keydown', '#input_area', function(e) {
if(e.which == 13) {
console.log("enterPressed");
}
});
$(document).on('click', '#unbindBtn', function(e) {
$(document).off('keydown', '#input_area');
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input id="input_area" placeholder="Tap Enter" />
<button id="unbindBtn">Unbind</button>
</body>
</html>

最新更新