目录 搜索
快速查询 核心 jQuery([selector,[context]]) jQuery(html,[ownerDocument]) jQuery(callback) jQuery.holdReady(hold) jQuery.readyException( error ) each(callback) size() length selector context get([index]) index([selector|element]) data([key],[value]) removeData([name|list]) jQuery.data(element,[key],[value]) queue(element,[queueName]) dequeue([queueName]) clearQueue([queueName]) jQuery.fn.extend(object) jQuery.extend(object) jQuery.noConflict([extreme]) 选择器 #id element .class * selector1,selector2,selectorN ancestor descendant parent > child prev + next prev ~ siblings :first :not(selector) :even :odd :eq(index) :gt(index) :lang(language) :last() :lt(index) :header :animated :focus :root :target :contains(text) :empty :has(selector) :parent :hidden :visible [attribute] [attribute=value] [attribute!=value] [attribute^=value] [attribute*=value] [selector1][selector2][selectorN] :first-child :first-of-type :last-child :last-of-type :nth-child :nth-last-child(n|even|odd|formula) :nth-last-of-type(n|even|odd|formula) :nth-of-type(n|even|odd|formula) :only-child :only-of-type :input :text :password :radio :checkbox :submit :image :reset :button :file :enabled :disabled :checked :selected $.escapeSelector(selector) AJAx $.ajax(url,[settings]) $.get(url,[data],[fn],[type]) $.getJSON(url,[data],[fn]) $.getScript(url,[callback]) $.post(url,[data],[fn],[type]) ajaxComplete(callback) ajaxError(callback) ajaxSend(callback) ajaxStart(callback) ajaxStop(callback) ajaxSuccess(callback) $.ajaxPrefilter([type],fn) $.ajaxSetup([options]) load(url, [data], [callback]) serialize() serializeArray() 属性 attr(name|properties|key,value|fn) removeAttr(name) prop(n|p|k,v|f) removeProp(name) addClass(class|fn) removeClass([class|fn]) toggleClass(class|fn[,sw]) html([val|fn]) text([val|fn]) val([val|fn|arr]) CSS css(name|pro|[,val|fn]) jQuery.cssHooks offset([coordinates]) position() scrollTop([val]) scrollLeft([val]) height([val|fn]) width([val|fn]) innerHeight() innerWidth() outerHeight([options]) outerWidth([options]) 文档处理 append(content|fn) appendTo(content) prepend(content|fn) prependTo(content) after(content|fn) before(content|fn) insertAfter(content) insertBefore(content) wrap(html|ele|fn) unwrap() wrapall(html|ele) wrapInner(html|ele|fn) replaceWith(content|fn) replaceAll(selector) empty() remove([expr]) detach([expr]) clone([Even[,deepEven]]) 筛选 eq(index|-index) first() last() hasClass(class) filter(expr|obj|ele|fn) is(expr|obj|ele|fn) map(callback) has(expr|ele) not(expr|ele|fn) slice(start,[end]) children([expr]) closest(e|o|e) find(e|o|e) next([expr]) nextAll([expr]) nextUntil([e|e][,f]) offsetParent() parent([expr]) parents([expr]) parentsUntil([e|e][,f]) prev([expr]) prevall([expr]) prevUntil([e|e][,f]) siblings([expr]) add(e|e|h|o[,c]) andSelf() addBack() contents() end() 事件 ready(fn) on(eve,[sel],[data],fn) off(eve,[sel],[fn]) bind(type,[data],fn) one(type,[data],fn) trigger(type,[data]) triggerHandler(type, [data]) unbind(t,[d|f]) live(type,[data],fn) die(type,[fn]) delegate(s,[t],[d],fn) undelegate([s,[t],fn]) hover([over,]out) toggle([s],[e],[fn]) blur([[data],fn]) change([[data],fn]) click([[data],fn]) dblclick([[data],fn]) error([[data],fn]) focus([[data],fn]) focusin([data],fn) focusout([data],fn) keydown([[data],fn]) keypress([[data],fn]) keyup([[data],fn]) mousedown([[data],fn]) mouseenter([[data],fn]) mouseleave([[data],fn]) mousemove([[data],fn]) mouseout([[data],fn]) mouseover([[data],fn]) mouseup([[data],fn]) resize([[data],fn]) scroll([[data],fn]) select([[data],fn]) submit([[data],fn]) unload([[data],fn]) 效果 show([s,[e],[fn]]) hide([s,[e],[fn]]) toggle([s],[e],[fn]) slideDown([s],[e],[fn]) slideUp([s,[e],[fn]]) slideToggle([s],[e],[fn]) fadeIn([s],[e],[fn]) fadeOut([s],[e],[fn]) fadeTo([[s],o,[e],[fn]]) fadeToggle([s,[e],[fn]]) animate(p,[s],[e],[fn]) stop([c],[j]) delay(d,[q]) finish([queue]) jQuery.fx.off jQuery.fx.interval 工具 $.support $.browser $.browser.version $.boxModel $.each(object,[callback]) $.extend([d],tgt,obj1,[objN]) $.grep(array,fn,[invert]) $.sub() $.when(deferreds) $.makearray(obj) $.map(arr|obj,callback) $.inArray(val,arr,[from]) $.toArray() $.merge(first,second) $.unique(array) $.uniqueSort(array) $.parseJSON(json) $.parseXML(data) $.noop $.proxy(function,context) $.contains(c,c) $.type(obj) $.isArray(obj) $.isFunction(obj) $.isEmptyObject(obj) $.isPlainObject(obj) $.isWindow(obj) $.isNumeric(value) $.trim(str) $.param(obj,[traditional]) $.error(message) $.fn.jquery 事件对象 eve.currentTarget eve.data eve.delegateTarget eve.isDefaultPrevented() eve.isImmediatePropag...() eve.isPropagationStopped() eve.namespace eve.pageX eve.pageY eve.preventDefault() eve.relatedTarget eve.result eve.stopImmediatePro...() eve.stopPropagation() eve.target eve.timeStamp eve.type eve.which 延迟对象 def.done(d,[d]) def.fail(failCallbacks) def.isRejected() def.isResolved() def.reject(args) def.rejectWith(c,[a]) def.resolve(args) def.resolveWith(c,[a]) def.then(d[,f][,p]) def.promise([ty],[ta]) def.pipe([d],[f],[p]) def.always(al,[al]) def.notify(args) def.notifyWith(c,[a]) def.progress(proCal) def.state() 回调函数 cal.add(callbacks) cal.disable() cal.empty() cal.fire(arguments) cal.fired() cal.fireWith([c] [,a]) cal.has(callback) cal.lock() cal.locked() cal.remove(callbacks) $.callbacks(flags) 正则表达式
文字

返回值:jQuery

live(type, [data], fn)

概述

jQuery 给所有匹配的元素附加一个事件处理函数,即使这个元素是以后再添加进来的也有效。

这个方法是基本是的 .bind() 方法的一个变体。使用 .bind() 时,选择器匹配的元素会附加一个事件处理函数,而以后再添加的元素则不会有。为此需要再使用一次 .bind() 才行。比如说

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

可以给这个元素绑定一个简单的click事件:

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

当点击了元素,就会弹出一个警告框。然后,想象一下这之后有另一个元素添加进来了。

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

尽管这个新的元素也能够匹配选择器 ".clickme" ,但是由于这个元素是在调用 .bind() 之后添加的,所以点击这个元素不会有任何效果。

.live() 就提供了对应这种情况的方法。如果我们是这样绑定click事件的:

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

然后再添加一个新元素:

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

然后再点击新增的元素,他依然能够触发事件处理函数。

事件委托

.live() 方法能对一个还没有添加进DOM的元素有效,是由于使用了事件委托:绑定在祖先元素上的事件处理函数可以对在后代上触发的事件作出回应。传递给 .live() 的事件处理函数不会绑定在元素上,而是把他作为一个特殊的事件处理函数,绑定在 DOM 树的根节点上。在我们的例子中,当点击新的元素后,会依次发生下列步骤:

  1. 生成一个click事件传递给                        来处理

  2. 由于没有事件处理函数直接绑定在 <divgt; 上,所以事件冒泡到DOM树上

  3. 事件不断冒泡一直到DOM树的根节点,默认情况下上面绑定了这个特殊的事件处理函数。

  4. 执行由 .live() 绑定的特殊的 click 事件处理函数。

  5. 这个事件处理函数首先检测事件对象的 target 来确定是不是需要继续。这个测试是通过检测 $(event.target).closest('.clickme') 能否找到匹配的元素来实现的。

  6. 如果找到了匹配的元素,那么调用原始的事件处理函数。

由于只有在事件发生时才会在上面的第五步里做测试,因此在任何时候添加的元素都能够响应这个事件。

附加说明

.live() 虽然很有用,但由于其特殊的实现方式,所以不能简单的在任何情况下替换 .bind()。主要的不同有:

  • 在jQuery 1.4中,.live()方法支持自定义事件,也支持所有的 JavaScript 事件。在jQuery 1.4.1中,甚至也支持 focus 和 blue 事件了(映射到更合适,并且可以冒泡的focusin和focusout上)。另外,在jQuery 1.4.1中,也能支持hover(映射到"mouseenter mouseleave")。然而在jQuery 1.3.x中,只支持支持的JavaScript事件和自定义事件:click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, 和 mouseup.

  • .live() 并不完全支持通过DOM遍历的方法找到的元素。取而代之的是,应当总是在一个选择器后面直接使用 .live() 方法,正如前面例子里提到的。

  • 当一个事件处理函数用 .live() 绑定后,要停止执行其他的事件处理函数,那么这个函数必须返回 false。 仅仅调用 .stopPropagation() 无法实现这个目的。

参考 .bind() 方法可以获得更多关于事件绑定的信息。

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

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

在jQuery 1.4.3中:你可以绑定一个或多个事件类型的字符串和函数的数据映射来执行他们

$("a").live({
  click: function() {
    // do something on click
  },
  mouseover: function() {
    // do something on mouseover
  }
});

在jQuery 1.4 中,data参数可以用于把附加信息传递给事件处理函数。一个很好的用处是应付由闭包导致的问题。可以参考 .bind() 的讨论来获得更多信息。

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

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

从 jQuery 1.7 开始,不再建议使用 .live() 方法。请使用 .on() 来添加事件处理。使用旧版本的用户,应该优先使用 .delegate() 来替代 .live()。

参数

type,[fn]String,FunctionV1.3

type:一个或多个事件类型,由空格分隔多个事件。

fn:要从每个匹配元素的事件中反绑定的事件处理函数

type,[data],falseString,Array,boolV1.4

type:一个或多个事件类型,由空格分隔多个事件。

data:传递给事件处理函数的附加参数

false:设置为false会使默认的动作失效。

eventStringV1.4.3

一个或多个事件类型的字符串和函数的数据映射来执行他们

示例

描述:

点击生成的p依然据有同样的功能。

HTML 代码:
<p>Click me!</p>
jQuery 代码:
$("p").live("click", function(){
    $(this).after("<p>Another paragraph!</p>");
});

描述:

阻止默认事件行为和事件冒泡,返回 false

jQuery 代码:
$("a").live("click", function() { return false; });

描述:

仅仅阻止默认事件行为

jQuery 代码:
$("a").live("click", function(event){
  event.preventDefault();
});


上一篇: 下一篇: