jquery中的.on()

来源:互联网 发布:郑州师范学院网络教育 编辑:程序博客网 时间:2024/05/17 07:35

原文:http://api.jquery.com/on/

译文参考:http://www.css88.com/


The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.

As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.

For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live().

To remove events bound with .on(), see .off().

To attach an event that runs only once and then removes itself, see .one()

.on()方法事件处理程序到当前选定的jQuery对象中的元素。

在jQuery 1.7中,.on()方法 提供绑定事件处理的所有功能。

为了帮助从旧的jQuery事件方法转换过来,查看 .bind(), .delegate(), 和 .live().

要删除的.on()绑定的事件,请参阅.off()

要绑定一个事件,并且只运行一次,然后删除自己, 请参阅.one()


Event names and namespaces

Any event names can be used for the events argument.

jQuery will pass through the browser's standard JavaScript event types, calling thehandler function when the browser generates events due to user actions such asclick.

In addition, the .trigger() method can trigger both standard browser event names and custom event names to call attached handlers.

Event names should only contain alphanumerics, underscore, and colon chraracters.

An event name can be qualified by event namespaces that simplify removing or triggering the event.

For example, "click.myPlugin.simple" defines both the myPlugin and simple namespaces for this particular click event.

A click event handler attached via that string could be removed with .off("click.myPlugin") or.off("click.simple")

without disturbing other click handlers attached to the elements.

Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match.

Namespaces beginning with an underscore are reserved for jQuery's use.

In the second form of .on(), the events argument is a plain object.

The keys are strings in the same form as the events argument with space-separated event type names and optional namespaces.

The value for each key is a function (or false value) that is used as thehandler instead of the final argument to the method.

In other respects, the two forms are identical in their behavior as described below.


任何事件的名称,都可以作为events 的参数。

当用户操作事件,如click,jQuery将传入所有浏览器的标准JavaScript事件类型,浏览器会调用handler参数的函数。

此外,.trigger()方法可以触发标准的浏览器事件 和 自定义事件名绑定的处理程序。

事件名称应该仅包含字母,数字,下划线和冒号。

事件名称可以添加指定的event namespaces(命名空间) 来简化删除或触发事件。

例如,"click.myPlugin.simple"为 click 事件同时定义了两个命名空间 myPlugin 和 simple。

通过上述方法绑定的 click 事件处理,可以用.off("click.myPlugin").off("click.simple")删除绑定到相应元素的Click事件处理程序,而不会干扰其他绑定在该元素上的“click(点击)” 事件。

命名空间类似CSS类,因为它们是不分层次的;只需要有一个名字相匹配即可。

以下划线开头的名字空间是供 jQuery 使用的。

.on()方法的第二种用法中,events参数是一个JavaScript对象或者键值对。

键等同于events参数,用空格分隔的事件名称字符串和可选的命名空间。

每个键的值是一个函数(或false 的值),相当于 handler 参数,但是该值并不是方法中的最后一个参数。

在其它方面,这两种形式在下面描述的内容中其行为都是相同的。如下所述。


Direct and delegated events

The majority of browser events bubble, or propagate, from the deepest, innermost element (theevent target) in the document where they occur all the way up to the body and thedocument element.

In Internet Explorer 8 and lower, a few events such as change andsubmit do not natively bubble but jQuery patches these to bubble and create consistent cross-browser behavior.

If selector is omitted or is null, the event handler is referred to asdirect ordirectly-bound.

The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

When a selector is provided, the event handler is referred to as delegated.

The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector.

jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.


Direct and delegated events(直接事件和委托/代理的事件)

大多数浏览器事件冒泡, 或者 传播,都是由内到外的,从在文档最深处的元素( 事件目标 event target)开始, 一路传递到body和document元素。

在Internet Explorer 8和更低版本,一些事件,如changesubmit本身不泡沫,但 jQuery 为了跨浏览器一致性, jQuery 在这些事件上模拟了冒泡行为。

如果省略selector或者是null,那么事件处理程序被称为直接事件 或者直接绑定事件

每次选中的元素触发事件时,就会执行处理程序,不管它直接绑定在元素上,还是从后代(内部)元素冒泡到该元素的。

当提供selector参数时,事件处理程序是指为委派 事件/代理事件。

事件不会在直接绑定的元素上触发,但只有当selector参数选择器匹配到后代(内部元素)的时候,事件处理函数才会被触发。

jQuery 会从 event target 开始向上层元素(例如,由最内层元素到最外层元素)开始冒泡,并且在传播路径上所有绑定了相同事件的元素若满足匹配的选择器,那么这些元素上的事件也会被触发。


Event handlers are bound only to the currently selected elements;

they must exist on the page at the time your code makes the call to .on().

To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlersafter the new HTML is placed into the page.

Or, use delegated events to attach an event handler, as described next.

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, ordocument 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()的时候,他们必须在页面文档中已经存在。

为了确保目前的元素可以被选择的,最好是在 document 的 ready 事件中进行事件绑定。

如果新的HTML被注入页面时,新的HTML放置到页面,事件会绑定到匹配选择器(selector参数)的元素。

或者,使用委派事件绑定事件处理程序,如下所述。

委托事件有一个优势,它可以处理后被加入的子元素的事件。

进行事件绑定时,在确保所选择的元素已经存在的情况下,您可以使用委派事件/代理事件,以避免频繁的绑定事件及解除绑定事件。

例如,这个已经存在的元素可以是 Model-View-Controller(模型 - 视图 - 控制器)模式中 View(视图) 的一个容器元素,或document

如果想监视所有文档中的冒泡事件的话。

在加载任何其它 HTML 之前,document 元素在 head 中就是有效的,所以您可以安全的在 head 中进行事件绑定,而不需要等待文档加载完。


In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in itstbody, this example attaches a handler to 1,000 elements:

除了可以给未创建的后代元素绑定事件外(即上面提到的优势),代理事件的另一个好处就是,当需要监视很多元素的时候,代理事件的开销更小。例如,在一个表格的 tbody 中含有 1,000 行,下面这个例子会为这 1,000 元素绑定事件:

1
2
3
$( "#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 clickedtr totbody):

委派事件的方法只有一个元素的事件处理程序,tbody,并且事件只会向上冒泡一层(从被点击的trtbody ):

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

Note: Delegated events do not work for SVG.

注意: 委托事件不能用于SVG.


The event handler and its environment

The handler argument is a function (or the value false, see below), and is required unless you pass an object for theevents argument. You can provide an anonymous handler function at the point of the.on() call, as the examples have done above, or declare a named function and pass its name:

handler参数必须是一个函数(或false值,见下文), 除非你传递一个对象给events参数。您可以提供一个匿名处理函数给.on()调用,就像上面例子中的用法,或者可以声明一个函数,然后再将该函数名作为参数:

1
2
3
4
function notify() {
alert( "clicked" );
}
$( "button" ).on( "click", notify );

When the browser triggers an event or other JavaScript calls jQuery's .trigger() method, jQuery passes the handler anevent object it can use to analyze and change the status of the event.

This object is a normalized subset of data provided by the browser; the browser's unmodified native event object is available inevent.originalEvent.

For example, event.type contains the event name (e.g., "resize") andevent.target indicates the deepest (innermost) element where the event occurred.

By default, most events bubble up from the original event target to the document element.

At each element along the way, jQuery calls any matching event handlers that have been attached.

A handler can prevent the event from bubbling further up the document tree (and thus prevent handlers on those elements from running) by callingevent.stopPropagation().

Any other handlers attached on the current element will run however. To prevent that, callevent.stopImmediatePropagation(). (Event handlers bound to an element are called in the same order that they were bound.)

Similarly, a handler can call event.preventDefault() to cancel any default action that the browser may have for this event; for example, the default action on aclick event is to follow the link.

Not all browser events have default actions, and not all default actions can be canceled. See theW3C Events Specification for details.

Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault().

A false value can also be passed for the handler as a shorthand forfunction(){ return false; }. So,$( "a.disabled" ).on( "click", false ); attaches an event handler to all links with class "disabled" that prevents them from being followed when they are clicked and also stops the event from bubbling.

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matchingselector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.)

To create a jQuery object from the element so that it can be used with jQuery methods, use$( this ).


当浏览器触发一个事件或其他JavaScript调用的jQuery的.trigger()方法,jQuery传递一个event object给这个处理程序,它可以用来分析和改变事件的状态。

这个对象是由浏览器提供一个数据的标注化子集;您需要浏览器自己的未经修改的原始 event 对象,您可以使用event.originalEvent得到。

例如, event.type 包含事件的名称(例如, "resize" )和event.target表示事件的最深元素(最内层),也就是事件发生的地方。

默认情况下,大多数事件的冒泡从最初的 event target(目标元素) 开始的,直到document 元素。

每个元素都沿着DOM层级这条路,jQuery会调用任何匹配的已被绑定的事件处理程序。

一个处理程序可以调用的event.stopPropagation()防止事件向上冒泡文档树( 从而防止这些元素的处理程序运行)。

任何绑定到当前元素上的其他处理程序都将运行,为了防止这种情况,可以调用event.stopImmediatePropagation()。(绑定在元素上的事件被调用的顺序和它们被绑定的顺序时一样的。 )

类似地,一个处理程序可以调用的event.preventDefault()取消浏览器默认操作行为;例如,一个链接上有一个 默认的click事件。并非所有的浏览器事件的默认操作,并非所有的默认操作可以被取消。有关详细信息,请参阅W3C Events Specification

(如果)从一个事件处理程序返回false,(事件处理程序)会自动调用event.stopPropagation()event.preventDefault()

也可以直接将 false 当作 handler 的参数,作为 function(){ return false; } 的简写形式。因此,下面的写法$("a.disabled").on("click", false);将会阻止所有含有 "disabled" 样式的链接的默认行为,并阻止该事件上的冒泡行为。

当jQuery的调用处理程序时,this关键字指向的是当前正在执行事件的元素。

对于直接事件而言,this 代表绑定事件的元素;对于代理事件而言,this 则代表了与selector 相匹配的元素。(注意,如果事件是从后代元素冒泡上来的话,那么this 就有可能不等于 event.target。)(应该是event.currentTarget)

若要使用 jQuery 的相关方法,可以根据当前元素创建一个 jQuery 对象,即使用 $(this)



Passing data to the handler(将数据传递到处理程序)

If a data argument is provided to .on() and is not null or undefined, it is passed to the handler in the event.data property each time an event is triggered. The data argument can be any type, but if a string is used theselector must either be provided or explicitly passed asnull so that the data is not mistaken for a selector. Best practice is to use a plain object so that multiple values can be passed as properties.

As of jQuery 1.4, the same event handler can be bound to an element multiple times. This is especially useful when theevent.data feature is being used, or when other unique data resides in a closure around the event handler function. For example:

如果data参数提供给.on()并且不是null 或者 undefined,那么每次触发事件时,通过event.data传递给处理程序。data参数可以是任何类型,但如果是字符串类型时,那么selector参数必须提供,或显式地传递null,这样的 话,data 参数不会被误认为是选择器。最好是使用一个对象(键值对) 以致于可以作为属性传递多个值。

jQuery的1.4 ,相同的事件处理程序可以多次绑定到一个元素。当使用 event.data 功能,或者在闭包中使用唯一的数据时,是特别有用的。例如:


1
2
3
4
5
6
7
8
9
function greet( event ) {
alert( "Hello " + event.data.name );
}
$( "button" ).on( "click", {
name: "Karl"
}, greet );
$( "button" ).on( "click", {
name: "Addy"
}, greet );

The above code will generate two different alerts when the button is clicked.

As an alternative or in addition to the data argument provided to the.on() method, you can also pass data to an event handler using a second argument to.trigger() or .triggerHandler().

按一下按钮时,上面的代码会产生两个不同的警报。

除了可以向 .on() 方法传入 data 参数外,还可以向 .trigger() 或 .triggerHandler() 中传入该参数。

Event performance(事件性能)

In most cases, an event such as click occurs infrequently and performance is not a significant concern. However, high frequency events such asmousemove orscroll can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates usingsetTimeout.

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use ofdocument ordocument.body for delegated events on large documents.

jQuery can process simple selectors of the form tag#id.class very quickly when they are used to filter delegated events. So,"#myForm","a.external", and "button" are all fast selectors. Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower--although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of$( "body" ).on( "click", "#commentForm .addNew", addComment ) use$( "#commentForm" ).on( "click", ".addNew", addComment ).


在大多数情况下,一个事件如click很少发生,性能表现并不明显。但是,高频率事件比如mousemove 或者scroll可以每秒触发几十个次,在这种情况下明智地使用事件变得更加重要。可以按如下的办法提高事件的性能:减少事件处理函数中的工作量;对于在事件处理函数中要用到的信息做好缓存而不是再重新计算一次;或使用setTimeout限制的页面更新的实际次数。

许多委派的事件处理程序绑定到 document 树的顶层附近会降低性能。每次发生事件时,jQuery 需要比较从 event target(目标元素) 开始到文档顶部的路径中每一个元素上所有该类型的事件。为了获得更好的性能,在绑定代理事件时,绑定的元素最好尽可能的靠近目标元素。在大型文档中,避免过多地在documentdocument.body 上添加代理事件。

jQuery可以非常迅速处理tag#id.class形式的简单选择器,当它们是用来过滤委派事件。所以"#myForm","a.external", 和"button" 都是快速选择器。若代理事件的选择器使用了过于复杂的形式,特别是使用了分层选择器的情况,虽然说这样做会大大的降低性能,但是对于大多数应用而言,它的速度依然是足够快的。通过为寻找更合适的元素绑定事件的方法,就可以很简单的避免使用分层选择器的情况。例如,使用$("#commentForm").on("click", ".addNew", addComment)而不是$("body").on("click", "#commentForm .addNew", addComment)


Additional notes

There are shorthand methods for some events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see theevents category.

Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string"mouseenter mouseleave". It attaches asingle event handler for those two events, and the handler must examineevent.type to determine whether the event ismouseenter ormouseleave. Do not confuse the "hover" pseudo-event-name with the.hover() method, which acceptsone or two functions.

jQuery's event system requires that a DOM element allow attaching data via a property on the element, so that events can be tracked and delivered. Theobject,embed, and applet elements cannot attach data, and therefore cannot have jQuery events bound to them.

The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browserfocusin andfocusout events that do bubble. When focus and blur are used to attach delegated event handlers, jQuery maps the names and delivers them asfocusin andfocusout respectively. For consistency and clarity, use the bubbling event type names.

In all browsers, the load, scroll, and error events (e.g., on an<img> element) do not bubble. In Internet Explorer 8 and lower, thepaste and reset events do not bubble. Such events are not supported for use with delegation, but theycan be used when the event handler is directly attached to the element generating the event.

The error event on the window object uses nonstandard arguments and return value conventions, so it is not supported by jQuery. Instead, assign a handler function directly to thewindow.onerror property.

有一些事件的速记方法比如.click()可用于附加或触发事件处理程序。对于速记方法的完整列表, 参见events category

在jQuery 1.8中被废止, 在1.9中被移除,伪类事件名称"hover"可以作为"mouseenter mouseleave"的缩写使用。不要与 接受两个函数的.hover()方法混淆,这里只用一个处理函数绑定到伪类事件名称"hover";处理程序应该检查的event.type 以确定是否是mouseentermouseleave事件。

jQuery的事件系统需要一个DOM元素可以通过元素的属性附加数据,使事件就可以被跟踪和传递。object, embed, 和applet元素不能绑定数据,因此不能有jQuery的事件绑定。

W3C指定明确指定focusblur事件没有冒泡,但是jQuery定义的跨浏览器的focusinfocusout事件,并且可以冒泡。focusblur绑定委派的事件处理程序时,jQuery分析名称,并提供将他们分别交付给focusinfocusout。为了保持一致性和清晰度,使用冒泡事件类型的名称。

在所有的浏览器,loadscroll, 和 error 事件(例如, 在一个<img> 元素上)不会冒泡。在Internet Explorer 8和更低,pastereset事件不会冒泡,这样的事件是不支持委派使用,但若事件处理函数是直接绑定在产生事件的元素上的话,是可以使用这些事件的。

window对象上的error 事件使用非标准的参数和返回值约定,所以jQuery 不支持该事件。作为替代,直接用window.onerror属性分配一个处理函数。















0 1
原创粉丝点击