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

时间:2015-10-28 16:09:19

标签: javascript html input enter onkeydown

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

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

我的问题是,如果他们在文本框中按输入键,则会启动我的function,并在button click之后调用myFunc()。< / p>

我使用过谷歌但无法解决问题,甚至在调用<!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> 时尝试禁用该按钮。

Grad = abs(Gx)+ abs(Gy)
Orient = ( atan2(Gy/Gx) * 180/3.14159265 ) + 180

5 个答案:

答案 0 :(得分:1)

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

<!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

答案 1 :(得分:1)

我认为这就是你要求的: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");
    }
}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

我已经在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>

答案 4 :(得分:0)

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

请参阅以下代码。

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

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

相关问题