event.preventDefault()在Chrome和Opera中不起作用 [英] event.preventDefault() does not work in Chrome and Opera

查看:349
本文介绍了event.preventDefault()在Chrome和Opera中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将jQuery验证插件1.9.0与jQuery 1.7.2一起使用.

I am using jQuery Validation Plugin 1.9.0 with jQuery 1.7.2.

我希望使用jquery验证插件来验证我的表单. 在Firefox 20.0.1和IE 10中运行正常. 但是在Chrome(26.0.1410.64 m)和Opera(12.14)中,我无法在表单中单击取消",而不会阻止进行验证.

I want my form to be validated with jquery validation plugin. It works fine in Firefox 20.0.1 and IE 10. But in Chrome (26.0.1410.64 m) and in Opera (12.14) I cannot click on cancel in my form without preventing validation to be done.

这是我的JavaScript代码:

This is my javascript code:

 submitHandler: function(form) {
  if (this.submitButton.value != 'cancel') {
   $(form).hide();
   $('#load').show();
   $(form).submit();
  }
  else {
  event.preventDefault();
  }
 }

当我单击FF和IE上的取消"时,可以按预期返回我的网站主页,但是当我在Chrome和Opera中执行此操作时,由于表单未完全填写,因此会显示错误消息. 在这两种情况下,都会调用event.preventDefault(),但根据浏览器的不同,行为似乎有所不同.

When I click on cancel on FF and IE I go back to my web home page as expected, but when I do this in Chrome and Opera my error messages are displayed as the form is incompletely filled. In both case the event.preventDefault() is called but it seems the behavior is different depending on the navigator.

您对什么地方有问题有任何想法吗?

Do you have any idea of what may be wrong ?

感谢您的帮助!

推荐答案

您误解了.preventDefault()的目的.这并不是为了防止函数的默认行为.它旨在取消常规元素的内置行为,即从定位标记等中删除导航和历史记录.

You are misunderstanding the purpose of .preventDefault(). It's not meant for preventing the default behavior of a function. It's meant for canceling the built-in behaviors of regular elements, i.e., remove the navigation and history from an anchor tag, etc.

请参阅: http://api.jquery.com/event.preventDefault/

AFAIK,您无法以编程方式打开和关闭验证.使用.validate()初始化插件后,将无法对其进行"un"初始化.

AFAIK, you cannot programatically turn validation on and off. Once you initialize the plugin with .validate(), there is no method to "un"-initialize it.

但是,仅使用取消"按钮,有几种方法...一种是确保将<form></form>的取消按钮放在之外,然后使用处理程序以执行其他操作.

However, to simply use a "cancel" button, there are several methods... one is to make sure you keep the cancel button outside of the <form></form> and then use a click handler to do something else with it.

演示: http://jsfiddle.net/TZVA6/1

Rocket Hazmat指出的另一种方法是为button提供一个type="button"属性,该属性可以防止默认的submit动作.

Or another method, as pointed out by Rocket Hazmat, is to give the button a type="button" attribute which prevents the default submit action.

演示: http://jsfiddle.net/TZVA6/2/

这篇关于event.preventDefault()在Chrome和Opera中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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