jquery中的.bind()

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

参考译文:http://www.css88.com/jqapi-1.9/bind/


As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the.bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elementsmust exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in.on() or .delegate().

从jQuery 1.7开始,.on() 方法是将事件处理程序绑定到文档(document)的首选方法。对于早期版本,.bind()方法用于直接附加一个事件处理程序到元素上。处理程序附加到jQuery对象中当前选中的元素,所以,在.bind()绑定事件的时候,这些元素必须已经存在。对于更为灵活的事件绑定,可以查看.on() 或者 .delegate()事件代理。

Any string is legal for eventType; if the string is not the name of a native DOM event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using.trigger() or .triggerHandler().

对于eventType任何字符串是合法的;如果该字符串不是一个原生的DOM事件名称,那么以自定义事件方式绑定处理程序。这些事件是不会被浏览器调用,但可以通过其他JavaScript代码,例如使用.trigger().triggerHandler() 来手动触发。

If the eventType string contains a period (.) character, then the event is namespaced. The period character separates the event from its namespace. For example, in the call.bind( "click.name", handler ), the string click is the event type, and the stringname is the namespace. Namespacing allows us to unbind or trigger some events of a type without affecting others. See the discussion of.unbind() for more information.

如果eventType参数字符串包含一个点( . )字符,那么该事件是带命名空间的。这个点( . )字符将事件及其命名空间分隔开来。例如,在调用.bind('click.name', handler) ,字符串click是事件类型,而字符串name是命名空间。命名空间允许我们解除或绑定一些事件,而不会影响其他事件(即使是同类型的事件,命名空间不同,就不会受到影响。)。见.unbind()获取更多信息。

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

有一些标准的浏览器事件的简写方法,比如 .click()可以使用附加或触发事件处理程序。简写方法的完整列表,请参阅events category

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

当事件到达一个元素,该元素上绑定的所有与之相对应的类型的事件都会被触发。如果该元素上有多个处理程序注册,他们将永远在其中按固定的次序执行。所有处理程序执行完成后,事件继续沿着正常的事件传播路径继续传播事件。

A basic usage of .bind() is:

1
2
3
       
       
$( "#foo" ).bind( "click", function() {
alert( "User clicked on 'foo.'" );
});

This code will cause the element with an ID of foo to respond to theclick event. When a user clicks inside this element thereafter, the alert will be shown.

此代码将使元素ID为foo响应click事件。当在用户点击这个元素之后,警报将显示。

Multiple Events(多个事件)

Multiple event types can be bound at once by including each one separated by a space:

多个事件类型可以通过用空格隔开一次性绑定:

1
2
3
       
       
$( "#foo" ).bind( "mouseenter mouseleave", function() {
$( this ).toggleClass( "entered" );
});

The effect of this on <div id="foo"> (when it does not initially have the "entered" class) is to add the "entered" class when the mouse enters the<div> and remove the class when the mouse leaves.

<div id="foo">(当最初它不会有"entered"样式类时)上的这个效果是当鼠标进入<div>时增加"entered"样式类,鼠标离开时移除这个样式类。

As of jQuery 1.4 we can bind multiple event handlers simultaneously by passing an object of event type/handler pairs:

在jQuery 1.4中,我们可以通过传递一个事件类型/处理函数的数据键值对映射来绑定多个事件处理程序,例如:

1
2
3
4
5
6
7
8
       
       
$( "#foo" ).bind({
click: function() {
// Do something on click
},
mouseenter: function() {
// Do something on mouseenter
}
});
Event Handlers(事件处理程序)

The handler parameter takes a callback function, as shown above. Within the handler, the keywordthis refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal$() function. For example:

handler参数需要一个回调函数,如上所述。在处理函数中, 关键字 this 指向当前所处理的 DOM 元素。为了该元素在jQuery中使用,它可以通过正常的$()函数。例如:

1
2
3
       
       
$( "#foo" ).bind( "click", function() {
alert( $( this ).text() );
});

After this code is executed, when the user clicks inside the element with an ID offoo, its text contents will be shown as an alert.

As of jQuery 1.4.2 duplicate event handlers can be bound to an element instead of being discarded. This is useful when the event data feature is being used, or when other unique data resides in a closure around the event handler function.

In jQuery 1.4.3 you can now pass in false in place of an event handler. This will bind an event handler equivalent to:function(){ return false; }. This function can be removed at a later time by calling:.unbind( eventName, false ).

执行此代码后,当用户点击里面ID为foo的元素 ,它的文本内容将被显示为警告。

在jQuery 1.4.2中,重复的事件处理程序可以绑定到一个元素,而不是被丢弃。这对于使用 event data 功能时,或者是当其它唯一的数据保存在事件处理函数的闭包中时,特别有用。

在jQuery1.4.3,您现在可以通过传递false代替一个事件处理程序。这将相当于一个事件处理程序绑定写成这样:function(){ return false; }。在以后通过调用.unbind( eventName, false )来移除这个函数。


The Event object(事件对象)

The handler callback function can also take parameters. When the function is called, the event object will be passed to the first parameter.

The event object is often unnecessary and the parameter omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered. However, at times it becomes necessary to gather more information about the user's environment at the time the event was initiated. View the full Event Object.

Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.

handler回调函数里还可以带参数。当函数被调用时,事件对象(event)将作为第一个参数被传递。

事件对象往往是不必要的,可以省略的参数,这是因为当触发事件处理时,我们可以通过上下文来取得足够的信息,完成我们需要的操作。然而,有的时候,当事件初始化完成时,我们需要收集更多关于用户环境的信息时,我们就需要使用该参数了。查看所有的事件对象

从一个处理函数返回false等效于调用事件对象中的.preventDefault().stopPropagation()


Using the event object in a handler looks like this:

1
2
3
4
5
6
7
      
      
$( document ).ready(function() {
$( "#foo" ).bind( "click", function( event ) {
alert( "The mouse cursor is at (" +
event.pageX + ", " + event.pageY +
")" );
});
});

Note the parameter added to the anonymous function. This code will cause a click on the element with IDfoo to report the page coordinates of the mouse cursor at the time of the click.

请注意,参数添加到匿名函数。此代码将使 在点击ID为foo的元素的时候 alert光标在页面上的坐标位置。

Passing Event Data(传递事件数据)

The optional eventData parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. For example, suppose we have two event handlers that both refer to the same external variable:

可选的eventData参数不常用。当提供时,这种参数允许我们给处理函数传递额外的信息。一个方便的使用这个参数来解决由于闭包造成的问题。例如,假设我们有两个事件处理函数都引用了相同的外部变量:

1
2
3
4
5
6
7
8
      
      
var message = "Spoon!";
$( "#foo" ).bind( "click", function() {
alert( message );
});
message = "Not in the face!";
$( "#bar" ).bind( "click", function() {
alert( message );
});

Because the handlers are closures that both have message in their environment, both will display the messageNot in the face! when triggered. The variable's value has changed. To sidestep this, we can pass the message in usingeventData:

由于两个事件处理函数的闭包中,都引用了 message,所以,当事件被触发时,这两个事件处理都会显示 Not in the face!,因为变量的值已经改变了。为了避免这个问题,我们可以使用 eventData 来传递信息:

1
2
3
4
5
6
7
8
9
10
11
12
      
      
var message = "Spoon!";
$( "#foo" ).bind( "click", {
msg: message
}, function( event ) {
alert( event.data.msg );
});
message = "Not in the face!";
$( "#bar" ).bind( "click", {
msg: message
}, function( event ) {
alert( event.data.msg );
});

This time the variable is not referred to directly within the handlers; instead, the variable is passed inby value through eventData, which fixes the value at the time the event is bound. The first handler will now displaySpoon! while the second will alert Not in the face!

这一次该变量没有提供给处理函数;相反,变量通过值传递给eventData ,所以就可以在事件绑定的时候进行赋值操作。第一个处理程序,现在将显示Spoon!而第二个会提醒Not in the face!。

Note that objects are passed to functions by reference, which further complicates this scenario.

If eventData is present, it is the second argument to the .bind() method; if no additional data needs to be sent to the handler, then the callback is passed as the second and final argument.

See the .trigger() method reference for a way to pass data to a handler at the time the event happens rather than when the handler is bound.

As of jQuery 1.4 we can no longer attach data (and thus, events) to object, embed, or applet elements because critical errors occur when attaching data to Java applets.

Note: Although demonstrated in the next example, it is inadvisable to bind handlers to both theclick and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before thedblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.


请注意,对象是通过参数传递给函数的,这种情况进一步复杂化。

如果eventData参数存在,那么第二个传递给.bind()的参数;如果没有更多的数据需要发送到处理程序,那么回调函数传递作为第二个也就是最后一个参数。

参考.trigger()方法来了解如何在事件发生时向事件处理函数中传入参数,而不是在事件绑定的时候传递数据。

从 jQuery 1.4 开始,我们再也不能附加数据(和事件)到对象,embed,或applet元素了, 因为当附加数据到Java的applet时会发生严重错误。

注意: 虽然表现在下面的例子中,  绑定 click 和dblClick事件处理程序到相同的元素,这是不可取的。 各个浏览器事件触发的顺序是不同的, 一些浏览器在dblclick之前接受两个 click 事件 ,而和其它浏览器只接受一个 click 事件。 用户往往可通过不同的操作系统和浏览器配置双击灵敏度( 点击之间的最大时间被检测为双击)。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值