我有一个文本输入和一个按钮(见下文)。我如何使用JavaScript触发按钮的点击事件时,进入键按下文本框内?

在我的当前页面上已经有一个不同的提交按钮,所以我不能简单地将该按钮设置为提交按钮。并且,我只想让Enter键单击这个特定的按钮,如果它是从这个文本框中按下,没有其他。

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />

当前回答

我的可重用Vanilla JS解决方案。因此,您可以根据激活的元素/文本框来更改点击哪个按钮。

 <input type="text" id="message" onkeypress="enterKeyHandler(event,'sendmessage')" />
 <input type="button" id="sendmessage" value="Send"/>

function enterKeyHandler(e,button) {
    e = e || window.event;
    if (e.key == 'Enter') {
        document.getElementById(button).click();
    }
}

其他回答

event.returnValue = false

在处理事件时或在事件处理程序调用的函数中使用它。

它至少在ie浏览器和Opera上运行。

这也可能有帮助,一个小的JavaScript函数,它工作得很好:

<script type="text/javascript">
function blank(a) { if(a.value == a.defaultValue) a.value = ""; }

function unblank(a) { if(a.value == "") a.value = a.defaultValue; }
</script> 
<input type="text" value="email goes here" onfocus="blank(this)" onblur="unblank(this)" />

我知道这个问题已经解决了,但我刚刚发现了一些东西,可以对其他人有所帮助。

我的可重用Vanilla JS解决方案。因此,您可以根据激活的元素/文本框来更改点击哪个按钮。

 <input type="text" id="message" onkeypress="enterKeyHandler(event,'sendmessage')" />
 <input type="button" id="sendmessage" value="Send"/>

function enterKeyHandler(e,button) {
    e = e || window.event;
    if (e.key == 'Enter') {
        document.getElementById(button).click();
    }
}

试一试:

<input type="text" id="txtSearch"/>
<input type="button" id="btnSearch" Value="Search"/>

<script>             
   window.onload = function() {
     document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {
        if (event.keyCode == 13) {
            document.getElementById('btnSearch').click();
        }
    };

    document.getElementById('btnSearch').onclick =doSomething;
}
</script>

在现代,undeprecated(没有keyCode或onkeydown) Javascript:

<input onkeypress="if(event.key == 'Enter') {console.log('Test')}">