jQuery:提交时不起作用 [英] JQuery: on submit doesn't work

查看:70
本文介绍了jQuery:提交时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试捕获所有表单提交事件,从action属性获取url,然后使用它使用AJAX将表单内容发送到该地址.所以我只需要一个提交事件处理程序.但是我很快遇到了麻烦,因为它似乎无法在IE中工作.

What I am trying is to catch all the form submit events, get the url from the action attribute and use it to send the content of the form to that address using AJAX. So what I need is only one on submit event handler. However I quickly got in trouble as it seems to not be working in IE.

$(document).submit(function(e) {
        alert('clicked');
        e.preventDefault();
    });  

这是我用于跨浏览器测试目的的代码.它在Chrome,Firefox中完美运行,但在IE中则无法正常运行.我是否不能在文档上设置事件监听器?

This is the code I use for cross-browser testing purpose. It works perfectly in Chrome, Firefox but not in IE. Am I not allowed to set an event listener on document?

推荐答案

看看jQuery API:

Have a look at the jQuery API:

JavaScript提交事件不会在Internet Explorer中冒泡.但是,依赖事件委托和Submit事件的脚本将在jQuery 1.4及更高版本的浏览器中始终如一地工作,从而规范了事件的行为. ( api.jquery.com/submit )

submit事件不会在Internet Explorer中冒泡,因此将永远不会将submit事件通知给document元素. jQuery会为您对此进行规范化,但前提是您使用事件委托.这并非难事,而且实际上如果复杂度更高,可能会使您的代码更好:

The submit event does not bubble in Internet Explorer, so the document element will never be notified of submit events. jQuery will normalise this for you, but only if you use event delegation. This is not difficult to do, and in fact may make your code nicer, if there is more complexity to it:

$(document).on('submit', 'form', function(e) {
    alert('clicked');
    e.preventDefault();
});

保留了绑定到document的优点(例如,捕获尚不存在的元素上的事件),同时在IE中使其成为可能.请注意,事件处理程序中的this现在是form元素,而不是document.

This keeps the advantages of binding to the document (e.g. capturing events on elements that don't yet exist), while making it possible in IE. Note that this, within the event handler, is now the form element, not the document.

这篇关于jQuery:提交时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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