使用“Enter Key”停止重新加载页面 [英] Stop reloading page with 'Enter Key'

查看:141
本文介绍了使用“Enter Key”停止重新加载页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面顶部有一个搜索框,当用户点击相邻按钮时会发出ajax调用。我正在尝试更新输入标记,以便当用户点击'enter'键时,适当的JavaScript将发生而不会重新加载页面。问题是页面不断重新加载。这是我最近的尝试:

I have a search box at the top of page that makes an ajax call when a user hits the adjacent button. I am trying to update the input tag so that when a user hit the 'enter' key, the apropriate JavaScript takes place without reloading the page. The problem is that the page keeps reloading. Here is my latest attempt:

$("searchText").bind('keyup', function(event){ 
  if(event.keyCode == 13){ 
    event.preventDefault();
    $("#buttonSrch").click(); 
    return false;
  }
});

<input type='search' id='searchText' />
<input type='button' id='buttonSrch' onclick="search(document.getElementById('searchText'))" value='Search' />


推荐答案

不要绑定到输入 S;绑定到表单。假设表格的I​​D为 searchForm

Don't bind to the inputs; bind to the form. Assuming the form has an ID of searchForm:

$("#searchForm").submit(function() {
    search($("#searchText").get(0));
    return false;
});

尝试一下。

Try it out.

也可以使用纯JavaScript来完成:

It can also be done with plain JavaScript:

document.getElementById('searchForm').addEventListener('submit', function(e) {
    search(document.getElementById('searchText'));
    e.preventDefault();
}, false);

这篇关于使用“Enter Key”停止重新加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆