提交表单时防止浏览器跳至首页 [英] Prevent browser jump to top page when submit the form

查看:73
本文介绍了提交表单时防止浏览器跳至首页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图防止用户提交表单时页面跳到顶部.很多人建议return false.但是,它也阻止了表单的提交.

I am trying to prevent the page jumping to top when the user submits the form. There are many people suggesting return false. However, it also prevents the form to be submitted too.

我想知道是否有人可以帮助我.

I was wondering if anyone could help me about it.

**JQuery**

$('#submit').click(function(){ //doesn't work
    return false;
})

$('form').submit(function(){  //doesn't work either
    return false;       
})



**Html**
<form...>
<input>...
<input>...
<input>...

<input type='submit' id='submit' value='submit'>

</form>

推荐答案

提交表单时,实际上是在加载新页面.在submit处理程序中返回false只是告诉浏览器不要使事件冒泡并且不执行默认事件,在这种情况下,默认事件是提交表单,这就是为什么执行此操作时什么都没有发生的原因.

When you submit the form you are effectively loading a new page. Returning false in the submit handler simply tells the browser not to bubble the event and not perform the default event, which in this case is submiting the form, which is why nothing is happening when you do this.

有几种解决您的问题的方法.如果您将用户(在提交表单后)重定向回表单页面,但出现错误,则可以在URL中包括片段标识符".使片段标识符指向您的表单ID,浏览器将自动转到文档的该部分.示例:

There are several solutions to your problem. If you are redirecting your user (after the form submission) back to the form page but with errors, you can include the "fragment identifier" in the url. Have the fragment identifier point to the ID of you form and the browser will automatically go to that part of the document. Example:

<form id="my-form">
    ...
</form>

您的网址为:

host/path?query=querystring#my-form

如果要避免重新加载页面,请尝试在JS中进行验证. jQuery验证插件非常易于使用,并且简直太棒了.请参阅此处,以了解如何使用它.很棒,因为它为您完成了大部分繁重的工作,并且具有一组常见的默认验证方法.

If you want to avoid having the page reload, try doing your validation in JS. The jQuery validation plugin is very easy to use and simply fantastic. See here to find out how to use it. It's great because it does most of the heavy lifting for you and has a set of common, default validation methods.

或者,您可以通过ajax提交表单,并返回服务器收到的任何验证错误.如果没有任何错误,则可以重定向到下一页.如果有错误,则将其粘贴在表单中或显示警报.此解决方案将避免您必须在客户端上复制任何复杂的验证逻辑(如果要使用jQuery validate插件).

Alternatively you can submit your form via ajax and return any validation errors that the server picks up. If you don't have any errors then you can redirect to the next page. If there are errors then stick them in the form or display an alert. This solution will avoid you having to replicate any complex validation logic on the client (if you want to use the jQuery validate plugin).

这篇关于提交表单时防止浏览器跳至首页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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