我已经创建了一个示例应用程序,可以检查我何时按下一个键或鼠标,但问题是当鼠标或按下键时它会打印控制台“按下Enter键”和“单击鼠标事件时未按Enter键”,布尔检查无法正常工作我认为如此,
任何人都可以告诉我一些解决方案
$('#adminPanel').bind("searchMaster", function(event, data)
{
var press = true;
$(this).keypress(function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13)
{
console.log("Enter is pressed");
press = false;
}
});
if(press)
{
console.log("Enter is not pressed, some Mouse event is clicked");
// some other action to be triggered if key is not pressed
}
});
答案 0 :(得分:1)
问题是,(a)您在点击回调中注册了按键事件,(b)您将press
设置为false
,是否按下了以及(c)您从未重置每次用鼠标点击时press
的值。
我建议你将两个回调分开并在回调之外移动press
。在示例中press
=> enterPressed
。 enterPressed
和回调包含在IIFE中,不会破坏全局命名空间。
(function () {
// by default, "enter" is not pressed
var enterPressed = false;
// Suppose this event is triggered by mouse clicks
$("#adminPanel").bind("searchMaster", function (event, data) {
if (!enterPressed) {
// Handle Mouse Click (no "enter" pressed here)
}
});
// This callback will be triggered if you press a key
// and if you release a key
$("#adminPanel").on("keydown keyup", function (e) {
var code = e.keyCode ? e.keyCode : e.which;
// check if the pressed/released key was "enter"
if (code === 13) {
enterPressed = !enterPressed;
}
});
})();