jQuery中的$(form).submit和$(form).on("submit")之间有什么区别? [英] What's the difference between $(form).submit and $(form).on("submit") in jQuery?

查看:1394
本文介绍了jQuery中的$(form).submit和$(form).on("submit")之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码,但不会在浏览器中导致AJAX调用:

I wrote the following code, which doesn't result in an AJAX call in my browser:

$(document).ready(function () {
  $('form').submit(function(event) {
    event.preventDefault();
    var action = $(this).attr('action');
    var data = $(this).serialize();
    $.post(action, data, function(response) {
      $("#die").html(response);
    });
  });
});

但是,我的讲师在班级现场编码了以下代码,该代码确实有效:

However, my instructor live-coded the following code in class, which does work:

$(document).ready(function () {
  $("form").on("submit", function(event) {
    event.preventDefault();
    var action = $(this).attr("action");
    var formData = $(this).serialize();
    $.post(action, formData, function(responseContent) {
      $("#die").html(responseContent);
    });
  });
});

据我所知,我的代码和他的代码之间唯一有意义的区别是在第2行上使用了"on"与"submit".实际上,在api.jquery.com/submit上,jQuery Foundation声明此方法是.on('submit',handler)...的快捷方式".这使我对两个片段为何表现不同感到困惑.

As far as I can tell, the only meaningful difference between my code and his is the use of 'on' vs. 'submit' on line 2. In fact, on api.jquery.com/submit, the jQuery Foundation states that "This method is a shortcut for .on('submit', handler)...". Which leaves me confused as to why the two snippets behave differently.

推荐答案

如果您查看jQuery .submit()文档

If you look at the jQuery .submit() docs

This method is a shortcut for .on('submit', handler)

它们的行为相同

正如您在jQuery的内部代码中看到的那样,使用速记版本将在内部调用.on()

As you can see in jQuery's internal code, using the shorthand version will internally call .on()

jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
    "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
    "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {

    // Handle event binding
    jQuery.fn[ name ] = function( data, fn ) {
        return arguments.length > 0 ?
            this.on( name, null, data, fn ) :
            this.trigger( name );
    };
});

这篇关于jQuery中的$(form).submit和$(form).on("submit")之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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