jQuery中$(form).submit和$(form).on(“submit”)之间的区别是什么? - 回这世界

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

$(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);
    });
  });
});

但是,我的教师在课堂上对以下代码进行了实时编码,这确实有效:

$(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)…“的快捷方式.这让我感到困惑的是为什么这两个片段表现不同.

解决方法

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

他们的行为相同

正如您在jQuery的内部代码中看到的那样,使用简写版本将在内部调用.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,fn ) :
            this.trigger( name );
    };
});

总结

以上是编程之家为你收集整理的jQuery中$(form).submit和$(form).on(“submit”)之间的区别是什么?全部内容。

点赞(0) 打赏

书签

技术

知识

立即下载

视频

导图

配色

教程

代码

素材

评论列表 0

暂无评论

发表评论 取消回复

分享
链接
快捷
记账
快捷
运动
热门
书签
菜单
显示
返回
顶部