2015-08-16 86 views
1

我是新手。我想添加代碼,除了光標點擊之外,還可以使用回車鍵在通過文本框提交的位置初始化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

回答

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

你會想要一個偵聽器添加到觸發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> 
1

這裏是您的解決方案:

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