我有点困惑以下工作方式?我将首先发布代码,html <form> <input type="text" id="guessInput" placeholder="A0" /> <input type="button" id="fireButton" value="Fire!" /> </form>js function handleFireButton(){ console.log("I am clicked");}function init(){ var fireButton = document.getElementById("fireButton"); fireButton.onclick = handleFireButton; var guessInput = document.getElementById("guessInput"); guessInput.onkeypress = handleKeyPress;}function handleKeyPress(e){ var fireButton = document.getElementById("fireButton"); if(e.keyCode === 13){ fireButton.click(); return false; }}window.onload = init;我的问题是,在其中init我可以理解第一部分,在fireButton.onclick = handleFireButton;中,单击该部分将激活该功能,但是下半部分让我有些困惑。我知道onkeypress何时会激活handleKeyPress并通过事件对象来检查keyCode === 13是否会激活fireButton.click(),但是这里没有提及任何有关激活handleFireButton()的信息,如何知道应该转到fireButton.click()吗? 最佳答案 在两个地方都具有相同的dom元素。您首先将事件处理程序附加到dom按钮。现在您正在从dom访问相同的按钮。并单击它。由于处理程序已经连接,因此将触发处理程序。关于javascript - 使用click()如何通过id激活此功能? (JavaScript),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34617863/
10-11 13:19