gpt4 book ai didi

javascript - HTML onKeyDown-事件调用函数和按钮点击

转载 作者:可可西里 更新时间:2023-11-01 13:28:48 24 4
gpt4 key购买 nike

我正在尝试创建一个搜索选项。

如果有人正在使用我的搜索字段,他们可以按“搜索按钮”或只需按 enter 键即可启动该功能。

我的问题是,如果他们在文本框中按下 enter 键,它会启动我的 function 并在 function 之后调用 点击按钮

我用谷歌但无法解决它,甚至试图在调用 myFunc() 时禁用按钮。

<!DOCTYPE html>
<html>
<body>
<form>Search
<br>
<input type="text" id="searchField" onKeyDown="if(event.keyCode==13) myFunc()">
<br>
<button type="button" id="myButton" onClick="myFunc()">Search</button>
</form>
</body>
</html>

最佳答案

在这种情况下,您似乎想停止事件传播。我已将您的代码更改为以下内容:

<!DOCTYPE html>
<html>
<body>

<form>
Search<br>
<input type="text" id="searchField" onKeyDown="if(event.keyCode==13){console.log('Hello World from Input'); return false;}">
<br>
<button type="button" id="myButton" onClick="console.log('Hello World from Button')">Search</button>
</form>
</body>
</html>

在输入元素具有焦点时按 enter 只会在控制台上显示 Hello World from Input

关于javascript - HTML onKeyDown-事件调用函数和按钮点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33396082/

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