$(document).on和$('#submit').on之间的区别 [英] Difference between $(document).on and $('#submit').on

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

问题描述

请让我知道以下内容之间的区别.

我对这种动作是陌生的.

 $('#myButton').on('click', function () {
            // Some code
        });

$(document).on('keyup', '#myButton', function () {
    // Some Code
});

$('#myButton').click(function () {
    //Some code
});

解决方案

来自文档


委派的事件的优势在于,它们可以处理以后在后代添加到文档中的后代元素中的事件.通过选择保证在附加委托事件处理程序时会出现的元素,您可以使用委托事件来避免频繁附加和删除事件处理程序的需要.例如,如果事件处理程序想要监视文档中的所有冒泡事件,则此元素可以是Model-View-Controller设计中视图的容器元素,也可以是文档.在加载任何其他HTML之前,文档元素位于文档的开头,因此可以在其中附加事件,而不必等待文档准备就绪.

在表体中有1,000行的数据表上,此示例将处理程序附加到1,000个元素:

$( "#dataTable tbody tr" ).on( "click", function() {
  alert( $( this ).text() );
});

委托事件方法将事件处理程序仅附加到一个元素,即tbody,而该事件仅需冒起一个层次(从单击的tr到tbody):

$( "#dataTable tbody" ).on( "click", "tr", function() {
  alert( $( this ).text() );
});

注意:委派的事件不适用于SVG.


另请参阅:

Please let me know the difference between the followings.

I am new to these kind of action.

 $('#myButton').on('click', function () {
            // Some code
        });

and

$(document).on('keyup', '#myButton', function () {
    // Some Code
});

and

$('#myButton').click(function () {
    //Some code
});

解决方案

From documentation


Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:

$( "#dataTable tbody tr" ).on( "click", function() {
  alert( $( this ).text() );
});

A delegated-events approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

$( "#dataTable tbody" ).on( "click", "tr", function() {
  alert( $( this ).text() );
});

Note: Delegated events do not work for SVG.


Also see:

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

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