javascript - 如何使用 click() 通过 id 激活此功能? (Javascript)

标签 javascript function onclick click

我有点困惑以下是如何工作的? 我先把代码贴出来

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() 何时激活应该转到handleFireButton()

最佳答案

click()函数触发一个点击事件,该事件由任何相关的事件监听器拾取。它本质上是模拟用户单击元素。

来自MDN :

The HTMLElement.click() method simulates a mouse click on an element.

When click is used with elements that support it (e.g. one of the <input> types listed above), it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an <a> element to initiate navigation as if a real mouse-click had been received.

所以,fireButton.click()没有打电话 handleFireButton()直接,而是生成一个事件,handleFireButton() onclick 事件监听器正在使用react。

关于javascript - 如何使用 click() 通过 id 激活此功能? (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34617863/

相关文章:

javascript - 我可以在 querySelectorAll 中使用正则表达式吗?

javascript - 从动态创建的 div 数组注册 onclick 事件? Rails + Jquery?

javascript - 选择框在转换后在 Firefox 中移动 :scale()

java - 阿克曼函数和递归

c - 即使参数计数正确,也无法运行的参数太少

function - SQL Server 2008 R2如何创建函数?

d3.js - 将单击事件绑定(bind)到上下文菜单列表元素

javascript - 值更改后,addeventlistener 中的变量未更新

javascript - React-native UI 挑战

javascript - href 不断将本地文件路径添加到 URL