【问题标题】:how do i trigger a "search" button via the Enter key如何通过 Enter 键触发“搜索”按钮
【发布时间】:2015-08-16 05:15:03
【问题描述】:

我是新手。我想添加代码,允许我使用回车键以及单击光标在通过文本框提交的位置初始化谷歌地图。我有点击部分,回车键,没有那么多:(

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

【问题讨论】:

  • 您能提供其余的代码吗?你没有付出太多。此外,请确保通过在每行代码前放置四个空格来正确格式化代码块。

标签: search enter


【解决方案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(){
	address=document.getElementById("address").value;
	//write your specific code from here	
	alert("You are searching: " + address);
}

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

</script>


</body>

</html>

如有任何疑问或建议,请随时提出。

【讨论】:

  • 格式化?解释?为什么要包括 jQuery?
【解决方案2】:
function search_func(e)
{
    e = e || window.event;
    if (e.keyCode == 13)
    {
        document.getElementById('search').click();
        return false;
    }
    return true;
}

【讨论】:

    【解决方案3】:

    您可能希望在文本框中添加一个侦听器,该侦听器在按下键时触发 search_func,当按下的键是 enter(13 是 enter 的 keyCode):

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

    【讨论】:

      猜你喜欢
      • 2012-10-20
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 2011-11-05
      • 2018-10-11
      相关资源
      最近更新 更多