简体   繁体   中英

How can I execute JavaScript function when the enter key is pressed

I just learnt web-dev 4 months ago and my first real project is a calculator and long story short, I want to display the result of a calculation when the user presses enter.

Heres my code:

var keyInput = function(e) {
    var eventObject = window.event ? event : e;
    var code = eventObject.charCode ? eventObject.charCode : eventObject.keyCode;
    var key = String.fromCharCode(code);
    if (!isNaN(Math.min(key))) {
        displayEntry(key);
    } else if (key === "/") {
        enterOperation("÷");
    } else if (key === "*") {
        enterOperation("×");
    } else if (key === "-") {
        enterOperation("-");
    } else if (key === "+") {
        enterOperation("+");
    } else if (key === "%") {
        enterOperation("%");
    } else if (unicode === 13) {
        e.preventDefault();
        displayResult('=');
    } else if (key === "c") {
        clearDisplay();
    }
};

document.onkeydown = keyInput;

It all works apart from enter (unicode === 13). What am I doing wrong? And why is the enter key printing the \\n character even though there are no text fields on the page?

You haven't set unicode... The \\n is added because it's the newline character added when you press enter. if you don't want it, you might want to remove the last character added.

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