如何通过回车键触发“搜索”按钮

问题描述:

我是新手。我想添加代码,除了光标点击之外,还可以使用回车键在通过文本框提交的位置初始化Google地图。我有点击的一部分下来,回车键,与其说:(如何通过回车键触发“搜索”按钮

<input id="address" type="text"> 
<input id="search" type="button" value="search" onClick="search_func()"> 

<script> 
    function search_func() { 
    var address = document.getElementById("address").value; 
    initialize(); 
    } 
</script> 
+0

你能提供你的其他代码吗?你没有给很多。此外,请确保在每行代码前放置四个空格,以正确格式化代码块。 – Tim

function search_func(e) 
{ 
    e = e || window.event; 
    if (e.keyCode == 13) 
    { 
     document.getElementById('search').click(); 
     return false; 
    } 
    return true; 
} 

你会想要一个侦听器添加到触发search_func上的keydown你的文本框,当按下的键是输入( 13是输入键代码):

<input id="address" type="text" onkeydown="key_down()"> 
<input id="search" type="button" value="search" onClick="search_func()"> 

<script> 
    function key_down(e) { 
    if(e.keyCode === 13) { 
     search_func(); 
    } 
    } 

    function search_func() { 
    var address = document.getElementById("address").value; 
    initialize(); 
    } 
</script> 

这里是您的解决方案:

<!DOCTYPE html> 
 

 
<html> 
 

 
<head> 
 
<title>WisdmLabs</title> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
 

 
<style> 
 

 
</style> 
 

 
</head> 
 

 
<body> 
 

 
<input id="address" type="text" onkeypress="handle(event)" placeholder="Type something here"> 
 
<input id="search" type="button" value="search" onClick="search_func()"> 
 

 
<script> 
 

 
function search_func(){ 
 
\t address=document.getElementById("address").value; 
 
\t //write your specific code from here \t 
 
\t alert("You are searching: " + address); 
 
} 
 

 
function handle(e){ 
 
\t address=document.getElementById("address").value; 
 
    if(e.keyCode === 13){ 
 
\t \t //write your specific code from here 
 
    \t alert("You are searching: " + address); 
 
    } 
 
\t return false; 
 
} 
 

 
</script> 
 

 

 
</body> 
 

 
</html>

随意问任何疑问或建议。

+0

格式?说明?你为什么包括jQuery? – rrowland