按 Enter 时如何调用 div 的点击处理程序?



这里的所有代码都运行得很好,我只是想让用户更容易,只需点击Enter即可执行函数,而不必点击div激活moneyFunction()

这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <title> YearlyDough </title>
    <link type="text/css" rel="stylesheet" href="money.css">
</head>
<body>
    <p id="header"> Enter yearly income </p>
    <input type="text" id="textmoney">
    <div onclick="moneyFunction()" id="moneydiv"> <p id="divtext">Calculate</p> </div>
    <p id="demo"></p>
    <p id="liar"></p>
    <div onclick="reloadFunction()" id="reload"> Redo </div>
    <a href="aboutmoney.html" id="about"> About </a>

    <script>
    function moneyFunction() {
        var money = document.getElementById('textmoney').value;
        var dailyE = money/365;
        document.getElementById('demo').innerHTML = ("$" + dailyE + " " + "per day");
    if ( document.getElementById('textmoney').value == 0) {
        document.getElementById('demo').innerHTML = "ERROR";
    }
    if ( document.getElementById('textmoney').value > 100000000000) {
            document.getElementById('liar').innerHTML = "I know you aint make that much.";
    } else {
        document.getElementById('liar').innerHTML = "";
    }
    }   
    function reloadFunction() {
        location.reload();
    } 
    </script>
</body>
</html>
var inp = document.getElementById("textmoney");
inp.addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {  //checks whether the pressed key is "Enter"
        moneyFunction();
    }
});
$('.div').click()

如果页面中包含jquery,那么在您的keydown事件内部将调用onclick。

最新更新