jquery的.live()和.bind的使用

.live( eventType, handler ) 返回:jQuery
附加一个事件处理器到符合目前选择器的所有元素匹配,现在和未来。
.bind( eventType, [ eventData ],handler(eventObject) ) 返回: jQuery
为一个元素绑定一个处理事件。

·        .live( eventType, handler)

eventTypeA string containing a JavaScriptevent type, such as "click" or "keydown." As of jQuery 1.4 thestring can contain multiple, space-separated event types or customevent names, as well.

handler每次事件触发时会执行的函数。

·        versionadded: 1.4.live( eventType, eventData, handler)

eventType一个包含一个JavaScript事件类型的字符串,比如"click"或"keydown"。在jQuery 1.4中,该字符串可以包含多个用空格分隔的事件类型或自定义事件名称。

eventData将要传递给事件处理函数的数据映射。

handler每次事件触发时会执行的函数。

这个方法是基于.bind()方法在元素上绑定事件处理器的一种变化。当.bind()被调用时,该元素的jQuery对象,是指附加处理器的元素;后面引入的让元素不能这样做,所以他们需要另一个.bind()调用。看下面的代码:

<body>
  <div class="clickme">
    Click here
  </div>
</body>

我们可以在这个元素上绑定一个简单的点击处理器:

$('.clickme').bind('click', function() {
  // Bound handler called.
});

当元素被点击时,该处理程序被调用。但是,假设在此之后,另一个因素被增加:

$('body').append('<div class="clickme">Another target</div>');

这个新元素也匹配.clickme选择器,但因为它是调用.bind()后再添加的,点击它什么都不会做。

.live()方法提供了一个可以替代的行为。如果我们绑定单击处理器到目标元素使用此方法:

$('.clickme').live('click', function() {
  // Live handler called.
});

再后来加入新元素:

$('body').append('<div class="clickme">Another target</div>');

然后点击新添加的元素也会触发的处理程序。

事件描述

.live()方法能影响尚未通过对事件的DOM方法添加的使用元素:绑定到父元素的处理程序是对于那些在其后代触发的事件负责。传递给处理器给.live()从不绑定到一个元素;相反, .live()绑定一个特殊的处理到DOM树的根。在我们的例子,当新的元素被点击,执行以下步骤:

1.   一个Click事件生成,并传递到 <div>处理。

2.   没有处理器是直接绑定到

,因此事件向上冒泡的DOM树。

3.   这个时间泡沫,直到它到达树的根,.live()默认情况下结合其特殊的处理。
* 在 jQuery1.4中, 事件冒泡可以随意停在 "context"DOM元素的。

4.   特别click通过.live()执行的处理器。

5.   此处理程序测试target的事件对象,看它是否应该继续下去。这项测试是由检查,如果$(event.target).closest('.clickme')是能够找到一个匹配的元素。

6.   如果找到一个匹配的元素,原来的处理程序被调用就可以了。

因为直到事件发生时在第5步不进行测试,元素可以在任何时候添加,仍然响应事件。.

更多信息见.bind()

Multiple Events

在jQuery 1.4.1 中,.live() 能接受多个,用空间分隔事件,在提供类似.bind()的功能。例如,我们可以“live ” 同时绑定mouseovermouseout事件,像这样:

$('.hoverme').live('mouseover mouseout', function(event) {
  if (event.type == 'mouseover') {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});
Event Data

在jQuery 1.4 中,可选eventData参数允许我们通过附加信息处理程序。一个方便的使用这个参数来解决由于闭包造成的问题。更多信息见"PassingEvent Data"。

Event Context

在jQuery 1.4 中,live事件可以绑定到“context”DOM元素,而不是默认的文档的根。要设置此背景下,我们通过在一个单一的DOM元素(而不是一个jQuery集合或选择器)使用jQuery() function'ssecond argument

$('div.clickme', $('#container')[0]).live('click', function() {
  // Live handler called.
});

The live handler in this example iscalled only when <divclass="clickme"> is a descendant of an element with anID of "container."

Caveats

The .live() technique is useful, but due to itsspecial approach cannot be simply substituted for .bind() in all cases. Specific differencesinclude:

·        DOM traversal methods are not fullysupported for finding elements to send to .live(). Rather, the .live() method should always be calleddirectly after a selector, as in the example above.

·        To stop further handlers fromexecuting after one bound using .live(), the handler must return false. Calling .stopPropagation() will not accomplish this.

·        In jQuery1.3.x only the followingJavaScript events (in addition to custom events) could be boundwith .live()clickdblclickkeydownkeypresskeyup,mousedownmousemovemouseoutmouseover, and mouseup.

·        As of jQuery1.4 the .live() method supports custom events as wellas all JavaScript events. As of jQuery1.4.1 even focus and blur work with live (mapping to the moreappropriate, bubbling, events focusin and focusout).

·        As of jQuery1.4.1 the hover event can be specified (mappingto mouseenter and mouseleave, which, in turn, are mappedto mouseover and mouseout).

Examples:

Example: Clicka paragraph to add another. Note that .live() binds the click eventto all paragraphs - even new ones.
<!DOCTYPE html>
<html>
<head>
  <style>
  p { background:yellow; font-weight:bold; cursor:pointer; 
      padding:5px; }
  p.over { background: #ccc; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Click me!</p>
 
  <span></span>
<script>
    $("p").live("click", function(){
      $(this).after("<p>Another paragraph!</p>");
    });
</script>
 
</body>
</html>
Demo:
Example: Todisplay each paragraph's text in an alert box whenever it isclicked:
$("p").live("click", function(){
  alert( $(this).text() );
});
Example: Tocancel a default action and prevent it from bubbling up, returnfalse:
$("a").live("click", function() { return false; })
Example: Tocancel only the default action by using the preventDefaultmethod.
$("a").live("click", function(event){
  event.preventDefault();
});
Example: Canbind custom events too.
<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; }
  span { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Has an attached custom event.</p>
  <button>Trigger custom event</button>
  <span style="display:none;"></span>
<script>
 
    $("p").live("myCustomEvent", function(e, myName, myValue){
      $(this).text("Hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent");
    });
 
</script>
 
</body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值