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

HTML onKeyDown-Event calling function and button-click

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

如果有人在使用我的搜索字段,他们可以按 "Search-Button" 或只需按 enter 键即可启动该功能。

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

我用过Google但无法解决,甚至试图在调用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

我想这就是你要的:https://jsfiddle.net/7vf9pz8u/1/

HTML

<form>Search
    <br>
    <input type="text" id="searchField" onKeyDown="pressEnter()">
    <br>
    <button type="button" id="myButton" onClick="myFunc()">Search</button>
</form>

JavaScript

function pressEnter() {
    if (event.keyCode == 13) {
        alert("working");
    }
}

我认为你应该阻止 event.preventDefault() 在 onkeydown 函数中提交表单。

我已经在 chrome 和 firefox 浏览器中测试了您的代码,它可以如您所愿地完美运行,我对您的代码进行了一些更新以表明它确实可以正常运行。关注:

<!DOCTYPE html>
<html>
<body>
<script>
function myFunc(){
    alert("Typed text.: "+document.getElementById("searchField").value) 
}
</script>
<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>

function (onEnter) 中单独处理 onKeyDown 并使用 event.preventDefault(); 阻止默认操作。

参见下面的代码。

window.onEnter = function () {
    if (event.keyCode == 13) {
        event.preventDefault();
        return false;
    }
}
<form>
  Search<br>
  <input type="text" id="searchField" onKeyDown="onEnter()">
  <br>
  <button type="button" id="myButton" onClick="myFunc()">Search</button>
</form>

http://jsfiddle.net/kishoresahas/cvyzLdy8/