gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:14:36 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com