在文本输入</button>中按Enter键时触发<按钮>

时间:2013-11-08 08:36:42

标签: javascript jquery html search button

我正在制作一个搜索栏,其中文本栏为标签,搜索按钮为a,我使用a而不是因为我使用了放大镜的图片在按钮上,当我使用它时,它并不想正确定位。

这是我的HTML:

<form id="search-form" href="#test1" class="smoothscroll">
            <input type="text" id="searchText" onClick="this.select();" placeholder="Search..."/>
            <button type="button" id="searchButton">
                <img src="magnify.png" id="magnify"/>
            </button>
        </form>

这是jquery:

$(document).ready(function () {
    $("#searchButton").click(function () {
        var text = document.getElementById('searchText').value;
        $("html, body").animate({
            scrollTop: ($('#' + text).offset().top)
        }, 2000);
    });

    $("#searchText").keyup(function (event) {
        if (event.keyCode == 13) {
            $("#searchButton").click();
        }
    });
}); 

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

根据docs,您应该使用.which代替keyCode:

$("#searchText").keyup(function(event){
    if(event.which == 13){
        $("#searchButton").click();
    }
    // Make sure the form isn't submitted
    event.preventDefault();
});
  

要确定按下了哪个键,请检查该事件对象   传递给处理函数。虽然浏览器使用不同   存储此信息的属性,jQuery规范化.which   属性,因此您可以可靠地使用它来检索密钥代码。

答案 1 :(得分:1)

试试这个

$("#searchText").keyup(function (event) {
    var code= event.keyCode ? event.keyCode : event.which;
    // or use simply, var code= event.keyCode || event.which;
    if (code == 13) {
        $("#searchButton").click();
    }
});

Demo

答案 2 :(得分:0)

$("#searchText").keyup(function(event){

  if (event.which === 13) {
    $("#searchButton").trigger("click");
   }  
});

另见Javascript .keyCode vs. .which?