简体   繁体   中英

boolean flag in javascript is not checking properly

i've created a sample application which checks when i press a key or mouse, but the problem is when mouse or when key is pressed it prints the console "Enter is pressed" and "Enter is not pressed some Mouse event is clicked" , that boolean checking is not working properly i think so,

can anyone please tell me some solution

$('#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
    }
});

The problem is, (a) that you register the keypress event inside the click callback and (b) that you set press to false , if is pressed and (c) that you never reset the value of press every time you click with the mouse.

I suggest you split the two callbacks up and move press outside of the callbacks. In the example press => enterPressed . The enterPressed and the callbacks are wrapped in an IIFE to not poluted the global namespace.

 (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;
        }
    });
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM