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

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

问题描述

我在页面顶部有一个搜索框,可以在用户点击相邻按钮时进行 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' />

推荐答案

Don't bind to the inputs;绑定到 form.假设 form 的 ID 为 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;
});

试试看.

它也可以用普通的 JavaScript 来完成:

It can also be done with plain JavaScript:

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

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

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