jQuery中$(form).submit和$(form).on("submit")之间的区别是什么?

Ric*_*mas 6 methods jquery

我编写了以下代码,这不会导致我的浏览器中的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);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

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

$(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);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

据我所知,我的代码之间的唯一有意义的区别是他的"上"与使用的第2行其实"提交",就api.jquery.com/submit,jQuery的基金会规定"此方法是.on('submit',handler)..."的快捷方式.这让我感到困惑的是为什么这两个片段表现不同.

Adr*_* Be 9

注意: .on()&.off()是写作时最新的jQuery语法(2014年8月).

如果您使用jQuery 1.7或以上,方法.bind(), .delegate().live()不应该被使用.这同样适用于.unbind(),.undelegate(),和.die().


介绍:

jQuery的.on('click')vs.click()类似,使用.on('submit')vs .submit()增加了许多优点:

来自andreister.on('click')vs .click()回答中,他指出内存使用量较小,我期望.on('submit')vs 相同.submit().

但对于.on('submit')vs来说.submit(),更重要的优势是某种"程序化的便利":

  1. 使用动态添加的元素
  2. 还提到了名称空间和引用(我在他的回答评论中指出)

请参阅下面的一些示例用法,了解这一切是如何运作的.


使用动态添加的元素:示例用法1

jsbin.com/puqahunovido/1/edit?html,js,console上查看现场演示(点击右上角的运行/清除)

基本上,你可以告诉jQuery"观察"一个元素是否有任何子代(直接或非直接)被提交.如果您向此元素动态添加新表单,这将特别有用.然后,您不需要将这些新表单"重新挂钩"到jQuery处理程序.


命名空间:示例用法1

jsbin.com/xalenefilifi/1/edit?html,js,console上查看现场演示(点击右上角的运行/清除)

/* bind form submission to 2 jQuery event handlers, each having a different namespace */
$(".js-form-hook-xyz").on("submit.hey", function() { console.log("hey!"); });
$(".js-form-hook-xyz").on("submit.hello", function() { console.log("hello!"); });

$(".js-form-hook-xyz").submit(); /* point 1: displays "hey!hello!" */

/* ... later in the code, unbind form submission for ONLY 1 handlers */
$(".js-form-hook-xyz").off("submit.hello");

$(".js-form-hook-xyz").submit(); /* point 2: displays "hey!" */
Run Code Online (Sandbox Code Playgroud)

结果是,如果表单在"第1点"提交,则两个处理程序都被附加,因此被调用.稍后,在"第2点"处理程序"submit.hello"不再附加,因此只有其他处理程序触发.


命名空间:示例用法2:

jsbin.com/vubolacozuwe/1/edit?html,js,console上查看现场演示(点击右上角的运行/清除)

/* bind form submission to 2 jQuery event handlers, each having the SAME namespace */
$(".js-form-hook-xyz").on("submit.greetings", function() { console.log("Bonjour!"); });
$(".js-form-hook-xyz").on("submit.greetings", function() { console.log("Hola!"); });

$(".js-form-hook-xyz").submit(); /* point 1: displays "Bonjour! Hola!" */

/* ... later in the code, unbind form submission for ".greetings" namespace handlers */
$(".js-form-hook-xyz").off(".greetings");

$(".js-form-hook-xyz").submit(); /* point 2: displays nothing, handlers were removed */
Run Code Online (Sandbox Code Playgroud)

结果是,如果表单在"第1点"提交,则两个处理程序都被附加,因此被调用.稍后,在"第2点"处理程序".greetings"命名空间处理程序已被删除,因此不会显示任何内容.


我现在可能会想到更多很酷的样本用法,所以我会把它留下来一段时间.只需查看jQuery文档并在SO或Google上搜索类似主题即可.你会发现一堆有趣的东西我敢肯定.

资源:

  1. .on('click')与.click()之间的区别
  2. 如何取消绑定特定的事件处理程序
  3. http://api.jquery.com/on/#event-names
  4. api.jquery.com/on
  5. api.jquery.com/submit


ᾠῗᵲ*_*ᵲᄐᶌ 5

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

此方法是.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, data, fn ) :
            this.trigger( name );
    };
});
Run Code Online (Sandbox Code Playgroud)

  • 我不同意这个答案。使用`.on('submit')`确实可以添加功能。看我的答案 (2认同)