无标题文档

jQuery API jQuery API 中英文对照版
关于本书

文档说明

    本文档旨在帮助广大javascript爱好者快速了解jquery库，以及供广大应用jquery进行开发的人员 提供一个速查手册！ 　　本文档资源来自于jquery.org.cn,部分内容直接翻译或copy自jquery.com！感谢jquery框架开发者 John Resig及其所在的jQuery team.为我们提供这么好的javascript开发类库，感谢jquery.org.cn为 翻译做出的努力！

注意事项

本文档大部分内容收集其网络，所以任何涉jQuery的法律及权益的问题与本文档整理者无关！

相关链接

jQuery官方网站 | jQuery中文网 | 电子书作者网站 | 电子书作者blog


关于jQuery

关于jQuery

jQuery 是一个新型的JavaScript库.

jQuery是一个简洁快速的JavaScript库，它能让你在你的网页上简单的操作文档、处理事件、运行动画效果或者添加Ajax交互。jQuery的设计会改变你写JavaScript代码的方式。

jQuery适合于设计师、开发者以及那些还好者，同样适合用于商业开发，可以说jQuery适合任何JavaScript应用的地方，可用于不用的应用程序。

jQuery是一个轻量级的脚本，其代码非常小巧，JavaScript包只有15K左右。

jQuery支持CSS1-CSS3,以及基本的xPath

jQuery是跨浏览器的，它支持的浏览器包括IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+

以下是英文原文：

jQuery is a new type of JavaScript library.

jQuery is a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. jQuery is designed to change the way that you write JavaScript.

"You start with 10 lines of jQuery that would have been 20 lines of tedious DOM JavaScript. By the time you are done it's down to two or three lines and it couldn't get any shorter unless it read your mind." - Dave Methvin

Learn about the jQuery JavaScript library

  • Designers,
  • Developers,
  • Hobbyists,
  • Businesses…

jQuery is for everyone.

The jQuery library is suited for many different applications.

How can jQuery help you?

  • Lightweight footprint

    · About 19KB in size (compressed)

  • CSS3 Compliant

    · Supports CSS 1-3 and basic XPath

  • Cross-browser

    · IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+

相关链接


jQuery入门指南

jQuery入门指南
jQuery入门指南

这个指南是一个对jQuery库的说明，要求读者了解DOM的一些常识。它包括了一个简单的Hello World的例子，选择器和事件基础，AJAX、FX的用法，以及如何制作jQuery的插件。

这个指南包括了很多代码，你可以copy它们，并试着修改它们，看看产生的效果。

内容提要

  1. 安装
  2. Hello jQuery
  3. Find me:使用选择器和事件
  4. Rate me:使用AJAX
  5. Animate me(让我生动起来):使用FX
  6. Sort me(将我有序化):使用tablesorter插件(表格排序)
  7. Plug me:制作您自己的插件
  8. Next steps(下一步)

一.安装
一开始,我们需求一个jQuery的库,最新的下载可以到这里找到。
这个指南提供一个基本包含实例的包供下载.

下载: jquery-starterkit

(译者Keel注:一定要下载这个包，光看文章不实践肯定是不行的。)

下载后解压缩，然后用你最喜欢的文本编辑器打开starterkit.html和custom.js这两个文件。
(译者Keel注:这两个就是例子文件,所有的例子都用这两个例子作出,custom.js写jQuery代码,starterkit.html观察效果.建议用editPlus打开)

现在,我们就已经做好了一切准备来进行这个著名的"Hello world"例子.

二.Hello jQuery在做所有事情之前,我们要让jQuery读取和处理文档的DOM,必须尽可能快地在DOM载入后开始执行事件,所以,我们用一个ready事件作为处理HTML文档的开始.看看我们打开的custom.js这个文件,里面已经准备好了:

$(document).ready(function() {
// do stuff when DOM is ready//当文档载入后从此处开始执行代码
});

下面我们放一个简单的alert事件在一个function中,因为这个alert不需求等DOM完成载入,所以我们把任务稍稍变复杂一点:在点击任何一个链接时显示一个alert.
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});

这样在你点击页面的一个链接时都会触发这个"Hello world"的提示。
(译者Keel注:请照此代码修改custom.js并保存,然后用浏览器打开starterkit.html观察效果。)

让我们看一下这些修改是什么含义。$("a") 是一个jQuery选择器(selector),在这里，它选择所有的a标签（译者Keel注：即<a></a>），$号是 jQuery “类”(jQuery "class")的一个别称，因此$()构造了一个新的jQuery 对象(jQuery object)。函数 click() 是这个jQuery对象的一个方法，它绑定了一个单击事件到所有选中的标签(这里是所有的a标签),并在事件触发时执行了它所提供的alert方法.
这里有一个拟行相似功能的代码:

<a href="#" onclick="alert('Hello world')">Link</a>

不同之处很明显,用jQuery不需要在每个a标签上写onclick事件,所以我们拥有了一个整洁的结构文档(HTML)和一个行为文档(JS),达到了将结构与行为分开的目的,就像我们使用CSS追求的一样.

下面我们会更多地了解到选择器与事件.

三.Find me:使用选择器和事件
jQuery提供两种方式来选择html的elements，第一种是用CSS和Xpath选择器联合起来形成一个字符串来传送到jQuery的构造器（如：$("div > ul a")）；第二种是用jQuery对象的几个methods(方法)。这两种方式还可以联合起来混合使用。

为了测试一下这些选择器，我们来试着在我们starterkit.html中选择并修改第一个ordered list.

一开始，我们需要选择这个list本身，这个list有一个ID叫“orderedlist”，通常的javascript写法是document.getElementById("orderedlist").在jQuery中，我们这样做：
$(document).ready(function() {
$("#orderedlist").addClass("red");
});

这里将starterkit中的一个CSS样式red附加到了orderedlist上(译者Keel注：参考测试包中的css目录下的core.css，其中定义了red样式)。因此，在你刷新了starterkit.html后，你将会看到第一个有序列表(ordered list )背景色变成了红色，而第二个有序列表没有变化.

现在，让我们添加一些新的样式到list的子节点.
$(document).ready(function() {
$("#orderedlist >
li").addClass("blue");
});

这样，所有orderedlist中的li都附加了样式blue。

现在我们再做个复杂一点的，当把鼠标放在li对象上面和移开时进行样式切换，但只在list的最后一个element上生效。
$(document).ready(function() {
$("#orderedlist
li:last").hover(function() {
$(this).addClass("green");
}, function() {
$(this).removeClass("green");
});
});

还有大量的类似的CSS和XPath例子，更多的例子和列表可以在这里找到。
（译者Keel注：入门看此文，修行在个人，要想在入门之后懂更多，所以这段话的几个链接迟早是要必看的！不会又要翻译吧...^_^!）

每一个onXXX事件都有效，如onclick,onchange,onsubmit等，都有jQuery等价表示方法（译者Keel注：jQuery不喜欢onXXX，所以都改成了XXX，去掉了on）。其他的一些事件，如ready和hover,也提供了相应的方法。

你可以在Visual jQuery找到全部的事件列表，在Events栏目下。

用这些选择器和事件你已经可以做很多的事情了，但这里有一个更强的好东东！

$(document).ready(function() {
$("#orderedlist").find("li").each(function(i) {
$(this).html(
$(this).html() + " BAM! " + i );
});
});

find() 让你在已经选择的element中作条件查找,因此 $("#orderedlist).find("li") 就像 $("#orderedlist li"). each()一样迭代了所有的li，并可以在此基础上作更多的处理。 大部分的方法,如addClass(), 都可以用它们自己的 each() 。在这个例子中, html()用来获取每个li的html文本, 追加一些文字，并将之设置为li的html文本。（译者Keel注：从这个例子可以看到.html()方法是获取对象的html代码，而.html('xxx')是设置'xxx'为对象的html代码）

另一个经常碰到的任务是在没有被jQuery覆盖的DOM元素上call一些方法，想像一个在你用AJAX方式成功提交后的reset：

$(document).ready(function() {
// use this to reset a
single form
$("#reset").click(function() {
$("#form")[0].reset();
});
});

（译者Keel注：这里作者将form的id也写成了form，源文件有<form id="form">，这是非常不好的写法，你可以将这个ID改成form1或者testForm，然后用$("#form1")或者$("#testForm")来表示它，再进行测试。）

这个代码选择了所有ID为"form"的元素，并在其第一个上call了一个reset()。如果你有一个以上的form，你可以这样做：

$(document).ready(function() {
// use this to reset
several forms at once
$("#reset").click(function() {
$("form").each(function() {
this.reset();
});
});
});

（译者Keel注：请注意一定要亲自将这些代码写在custom.js中并在starterkit.html上测试效果才能有所体会！必要时要观察starterkit.html的html代码）

这样你在点击Reset链接后，就选择了文档中所有的form元素，并对它们都执行了一次reset()。

还有一个你可能要面对的问题是不希望某些特定的元素被选择。jQuery 提供了filter() 和not() 方法来解决这个问题。 filter()以过滤表达式来减少不符合的被选择项, not()则用来取消所有符合过滤表达式的被选择项. 考虑一个无序的list，你想要选择所有的没有ul子元素的li元素。

$(document).ready(function() {
$("li").not("[ul]").css("border", "1px solid black");
});

这个代码选择了所有的li元素，然后去除了没有ul子元素的li元素。刷新浏览器后，所有的li元素都有了一个边框，只有ul子元素的那个li元素例外。

（译者Keel注：请注意体会方便之极的css()方法，并再次提醒请务必实际测试观察效果，比方说换个CSS样式呢？再加一个CSS样式呢？像这样：$("li").not("[ul]").css("border", "1px solid black").css("color","red");）

上面代码中的[expression] 语法是从XPath而来，可以在子元素和属性(elements and attributes)上用作过滤器，比如你可能想选择所有的带有name属性的链接：
$(document).ready(function() {
$("a[@name]").background("#eee");
});

这个代码给所有带有name属性的链接加了一个背景色。（译者Keel注：这个颜色太不明显了，建议写成$("a[@name]").background("red");）

更常见的情况是以name来选择链接，你可能需要选择一个有特点href属性的链接，这在不同的浏览器下对href的理解可能会不一致，所以我们的部分匹配("*=")的方式来代替完全匹配("=")：
$(document).ready(function() {
$("a[@href*=/content/gallery]").click(function() {
// do something with
all links that point somewhere to /content/gallery
});
});

到现在为止，选择器都用来选择子元素或者是过滤元素。另外还有一种情况是选择上一个或者下一个元素，比如一个FAQ的页面，答案首先会隐藏，当问题点击时，答案显示出来，jQuery代码如下：
$(document).ready(function() {
$('#faq').find('dd').hide().end().find('dt').click(function() {
var
answer = $(this).next();
if (answer.is(':visible')) {
answer.slideUp();
} else {
answer.slideDown();
}
});
});

这里我们用了一些链式表达法来减少代码量，而且看上去更直观更容易理解。像'#faq' 只选择了一次，利用end()方法，第一次find()方法会结束(undone)，所以我们可以接着在后面继续find('dt')，而不需要再写$('#faq').find('dt')。

在点击事件中的，我们用 $(this).next() 来找到dt下面紧接的一个dd元素，这让我们可以快速地选择在被点击问题下面的答案。
（译者Keel注：这个例子真是太酷了，FAQ中的答案可以收缩！从利用next()的思路到实现这些效果都有很多地方需要我们消化，注意 if (answer.is(':visible'))用法，注意answer.slideUp();不懂的地方赶紧查我在最开始提到的两个必看API文档）

除了选择同级别的元素外，你也可以选择父级的元素。可能你想在用户鼠标移到文章某段的某个链接时，它的父级元素--也就是文章的这一段突出显示，试试这个：
$(document).ready(function() {
$("a").hover(function() {
$(this).parents("p").addClass("highlight");
}, function() {
$(this).parents("p").removeClass("highlight");
});
});

测试效果可以看到，移到文章某段的链接时，它所在的段全用上highlight样式，移走之后又恢复原样。
（译者Keel注：highlight是core.css中定义的样式，你也可以改变它，注意这里有第二个function()这是hover方法的特点，请在API文档中查阅hover，上面也有例子说明）

在我们继续之前我们先来看看这一步： jQuery会让代码变得更短从而更容易理解和维护，下面是$(document).ready(callback)的缩写法：
$(function() {
// code to execute when the DOM is ready
});

应用到我们的Hello world例子中，可以这样：
$(function() {
$("a").click(function() {
alert("Hello world!");
});
});

现在，我们手上有了这些基础的知识，我们可以更进一步的探索其它方面的东西，就从AJAX开始！
四.Rate me:使用AJAX
在这一部分我们写了一个小小的AJAX应用，它能够rate一些东西（译者Keel注：就是对某些东西投票），就像在youtube.com上面看到的一样。
首先我们需要一些服务器端代码，这个例子中用到了一个PHP文件，读取rating参数然后返回rating总数和平均数。看一下rate.php代码。

虽然这些例子也可以不使用AJAX来实现，但显然我们不会那么做，我们用jQuery生成一个DIV容器，ID是"rating"。
$(document).ready(function() {
// generate markup
var ratingMarkup = ["Please rate: "];
for(var i=1; i <= 5; i++) { ratingMarkup[ratingMarkup.length] = "" +
i + " ";
}
// add markup to container and
applier click handlers to anchors
$("#rating").append( ratingMarkup.join('')
).find("a").click(function(e) {
e.preventDefault();
// send requests
$.post("rate.php", {rating: $(this).html()}, function(xml) {
// format
result
var result = [
"Thanks for rating, current average: ",
$("average", xml).text(),
", number of votes: ",
$("count",
xml).text()
];
// output result
$("#rating").html(result.join(''));
} );
});
});

这段代码生成了5个链接，并将它们追加到id为"rating"容器中，当其中一个链接被点击时，该链接标明的分数就会以rating参数形式发送到rate.php，然后，结果将以XML形式会从服务器端传回来，添加到容器中，替代这些链接。
如果你没有一个安装过PHP的webserver，你可以看看这个在线的例子。
这是一个比较粗糙的例子，更完美的例子可以访问 softonic.de 点击 "Kurz bewerten!"。
更多的AJAX方法可以从这里找到，或者看看API文档下面的AJAX。

（译者Keel注：这个在线实例从国内访问还是比较慢的，点击后要等一会儿才能看到结果，可以考虑对它进行修改，比如加上loading，投票后加上再投票的返回链接等。此外，这个例子中还是有很多需要进一步消化的地方，看不懂的地方请参考API文档。）

一个在载入AJAX时经常发生的问题是：当载入一个事件句柄到一个需要载入内容的HTML文档时，你只能在内容载入后再加载这些句柄，为了防止代码重复执行，你可能用到如下一个function:
// lets use the shortcut
$(function() {
var
addClickHandlers = function() {
$("a.clickMeToLoadContent").click(function()
{
$("#target").load(this.href, addClickHandlers);
});
};
addClickHandlers();
});

现在，addClickHandlers只在DOM载入完成后执行一次，并且是在用户点击具有clickMeToLoadContent 这个样式的链接后。

请注意addClickHandlers函数是作为一个本地变量定义的，而不是全局变量(如：function addClickHandlers() {...})，这样做是为了防止与其他的全局变量或者函数相冲突。

另一个常见的问题是关于回传(callback)的参数。你可以通过一个额外的参数指定回叫的方法，简单的办法是将这个回叫方法包含在一个其它的function中：
// get some data
var foobar = ...;
// specify
handler, it needs data as a paramter
var handler = function(data) {
...
};
// add click handler and pass foobar!
$('a').click(
function(event) { handler(foobar); } );

// if you need the context of
the original handler, use apply:
$('a').click( function(event) {
handler.apply(this, [foobar]); } );

用到简单的AJAX后，我们可以认为已经非常之“web2.0”了，但是到现在为止，我们还缺少一些酷炫的效果。下一节将如谈到这些效果。

五：Animate me(让我生动起来):使用FX

一些生动的效果可以使用 show() 和 hide()来表现:

$(document).ready(function() {
 $("a").toggle(function() {
  $(".stuff").hide('slow');
 }, function() {
  $(".stuff").show('fast');
 });
});

你可以与 animate()联合起来创建一些效果,如一个带渐显的滑动效果:

$(document).ready(function() {
 $("a").toggle(function() {
  $(".stuff").animate({
   height: 'hide',
   opacity: 'hide'
  }, 'slow');
 }, function() {
  $(".stuff").animate({
   height: 'show',
   opacity: 'show'
  }, 'slow');
 });
});

很多不错的效果可以访问interface plugin collection. 这个站点提供了很多demos和文档

这些效果插件是位于jQuery插件列表的前面的，当然也有很多其他的插件，比如我们下一章讲到的表格排序插件。

六、Sort me(将我有序化):使用tablesorter插件(表格排序)

这个表格排序插件能让我们在客户端按某一列进行排序，引入jQuery和这个插件的js文件，然后告诉插件你想要哪个表格拥有排序功能。

要测试这个例子，先在starterkit.html中加上像下面这一行的代码：

<script src="lib/jquery.tablesorter.js" type="text/javascript"></script>

然后可以这样调用不着:

$(document).ready(function() {
 $("#large").tableSorter();
});

现在点击表格的第一行head区域，你可以看到排序的效果，再次点击会按倒过来的顺序进行排列。

这个表格还可以加一些突出显示的效果，我们可以做这样一个隔行背景色效果:

$(document).ready(function() {
 $("#large").tableSorter({
// Class names for striping supplyed as a array.
  stripingRowClass: ['odd','even'],
  stripRowsOnStartUp: true  // Strip rows on tableSorter init.
 });
});

关于这个插件的更多例子和文档可以在 tablesorter首页找到.

几乎所有的特件都是这样用的:先include插件的js文件,然后在某些元素上使用插件定义的方法,当然也有一些参数选项是可以配置的

经常更新的插件列表可以从jQuery官方站 on the jQuery site找到.

当你更经常地使用jQury时,你会发现将你自己的代码打包成插件是很有用处的,它能方便地让你的公司或者其他人进行重用.下一章我们将谈到如何构建一个自己的插件.

七、Plug me:制作自己的插件

写一个自己的jQuery插件是非常容易的,如果你按照下面的原则来做,可以让其他人也容易地结合使用你的插件.

  1. 为你的插件取一个名字,在这个例子里面我们叫它"foobar".
  2. 创建一个像这样的文件:jquery.[yourpluginname].js,比如我们创建一个jquery.foobar.js
  3. 创建一个或更多的插件方法,使用继承jQuery对象的方式,如:

    jQuery.fn.foobar = function() {
     // do something
    };
  4. 可选的:创建一个用于帮助说明的函数,如:

    jQuery.fooBar = {
     height: 5,
     calculateBar = function() { ... },
     checkDependencies = function() { ... }
    };

    你现在可以在你的插件中使用这些帮助函数了:

    jQuery.fn.foobar = function() {
     // do something
     jQuery.foobar.checkDependencies(value);
     // do something else
    };
  5. 可选的l:创建一个默认的初始参数配置,这些配置也可以由用户自行设定,如:

    jQuery.fn.foobar = function(options) {
     var settings = {
      value: 5,
      name: "pete",
      bar: 655
     };
     if(options) {
      jQuery.extend(settings, options);
     }
    };

    现在可以无需做任何配置地使用插件了,默认的参数在此时生效:

    $("...").foobar();

    Or with some options:

    $("...").foobar({
     value: 123,
     bar: 9
    });

如果你release你的插件, 你还应该提供一些例子和文档,大部分的插件都具备这些良好的参考文档.

现在你应该有了写一个插件的基础,让我们试着用这些知识写一个自己的插件.

很多人试着控制所有的radio或者checkbox是否被选中,比如:

$("input[@type='checkbox']").each(function() {
 this.checked = true;
 // or, to uncheck
 this.checked = false;
 // or, to toggle
 this.checked = !this.checked;
});

你可能想要把这个重写为一个插件,很直接地:

$.fn.check = function() {
 return this.each(function() {
  this.checked = true;
 });
};

这个插件现在可以这样用:

$("input[@type='checkbox']").check();

现在你应该还可以写出uncheck()和toggleCheck()了.但是先停一下,让我们的插件接收一些参数.

$.fn.check = function(mode) {
 var mode = mode || 'on'; // if mode is undefined, use 'on' as default
 return this.each(function() {
  switch(mode) {
  case 'on':
   this.checked = true;
   break;
  case 'off':
   this.checked = false;
   break;
  case 'toggle':
   this.checked = !this.checked;
   break;
  }
 });
};

这里我们设置了默认的参数,所以将"on"参数省略也是可以的,当然也可以加上"on","off", 或 "toggle",如:

$("input[@type='checkbox']").check();
$("input[@type='checkbox']").check('on');
$("input[@type='checkbox']").check('off');
$("input[@type='checkbox']").check('toggle');

如果有多于一个的参数设置会稍稍有点复杂,在使用时如果只想设置第二个参数,则要在第一个参数位置写入null.

从上一章的tablesorter插件用法我们可以看到,既可以省略所有参数来使用或者通过一个 key/value 对来重新设置每个参数.

作为一个练习,你可以试着将 第四部分 的功能重写为一个插件.这个插件的骨架应该是像这样的:

$.fn.rateMe = function(options) {

 // instead of selecting a static container with $("#rating"),
 //we now use the jQuery context
 var container = this;

 var settings = {
  url: "rate.php"
  // put more defaults here
  // remember to put a comma (",") after each pair,
  // but not after the last one!
 };

 if(options) {
 // check if options are present before extending the settings
  $.extend(settings, options);
 }

 // ...
 // rest of the code
 // ...

 return this; // if possible, return "this" to not break the chain
});
Next steps(下一步)

如果你想做更好的javascript开发,建议你使用一个叫 FireBug的firefox插件. 它提供了断点调试(比alert强多了)、观察DOM变化等很多漂亮的功能

如果你还有未解决的问题，或者新的想法与建议，你可以使用jQuery的邮件列表 jQuery mailing list.

关于这个指南的任何事情，你可以写mail给作者或者发表评论在他的日志：blog.


Core

Core

jQuery的核心部分。

jQuery $(Element|Array<Element> elements)为一个或多个DOM元素捆绑jQuery功能。

jQuery $(String html) 根据提供的原始HTML标记字符串，动态创建由jQuery对象包装的DOM元素。

jQuery $(Function fn) $(document)的简写方式。

jQuery $(String expr,Element|jQuery context) 这个函数接收一个包含CSS或基本的XPath选择符的字符串，然后用这个字符串去匹配一组元素。

jQuery $.extent(Object prop) 扩展jQuery对象

Object $.extent(Object target,Object prop1,Object propn) 用一个或多个其他对象来扩展一个对象，返回这个被扩展的对象。

undefined $.noConflict() 运行这个函数将变量$的控制权让渡给第一个实现它的那个库。

jQuery each(Function fn) 以每一个匹配的元素作为上下文来执行一个函数。

jQuery eq(Number pos) 将匹配的元素集合缩减为一个元素。

Array<Element> get() 取得所有匹配的元素

Element get(Number num) 取得其中一个匹配的元素。

jQuery gt(Number pos) 将匹配的元素集合缩减为给定位置之后的所有元素。

Number index(Element subject) 搜索与参数表示的对象匹配的元素，并返回相应元素的索引值。

Number length 当前匹配的元素数量。

jQuery lt(Number pos) 将匹配的元素集合缩减为给定位置之前的所有元素。

Number size() 当前匹配的元素数量。


$(elements)

$(elements)
$(elements)

为一个或多个DOM元素捆绑jQuery功能。

这个函数也可以接收XML文档和Window对象（虽然它们不是DOM元素）作为有效的参数。

返回值: jQuery

参数:
  • elements (Element|Array<Element>): 由jQuery对象封装的DOM元素
示例1:

与 $("div > p") 相同。

HTML 代码:

<p>one</p> <div><p>two</p></div> <p>three</p>

jQuery 代码:

$(document).find("div > p")

结果:

[ <p>two</p> ]

示例2:

把页面的背景颜色设置为黑色。

Sets the background color of the page to black.

jQuery 代码:

$(document.body).background( "black" );

示例3:

隐藏表单中的所有input元素。

Hides all the input elements within a form

jQuery 代码:

$( myForm.elements ).hide()

$( elems )

Wrap jQuery functionality around a single or multiple DOM Element(s).

This function also accepts XML Documents and Window objects as valid arguments (even though they are not DOM Elements).

Return value: jQuery
Parameters:

  • elems (Element|Array<Element>): DOM element(s) to be encapsulated by a jQuery object.

Example:

Sets the background color of the page to black.

$(document.body).css( "background", "black" );

Example:

Hides all the input elements within a form

$( myForm.elements ).hide()


$(expr,context)

$(expr,context)
$(expr, context)

这个函数接收一个包含CSS或基本的XPath选择符的字符串，然后用这个字符串去匹配一组元素。

jQuery的核心功能都是通过这个函数实现的。 jQuery中的一切都构建于这个函数之上，或者说都是在以某种方式使用这个函数。这个函数最基本的用法就是向它传递一个表达式（通常由CSS或XPath选择符组成），然后根据这个表达式来查询所有匹配的元素。

在默认情况下，$()查询的是当前HTML文档中的DOM元素。

返回值:jQuery

参数:

  • expr (String): 用来查询用的字符串
  • context (Element|jQuery): （可选）作为上下文的DOM元素、文档或jQuery对象。
示例:

找到所有是div元素子元素的p元素。

HTML 代码:

<p>one</p> <div><p>two</p></div> <p>three</p>

jQuery 代码:

$("div > p")

结果:

[ <p>two</p> ]

示列：

在文档的第一个表单中，搜索所有单选按钮（或：type值为radio的input元素）。

jQuery 代码:

$("input:radio", document.forms[0])

示列：

查询指定XML文档中的所有div元素。

jQuery 代码:

$("div", xml.responseXML)

$( expr, context )

This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements.

The core functionality of jQuery centers around this function. Everything in jQuery is based upon this, or uses this in some way. The most basic use of this function is to pass in an expression (usually consisting of CSS or XPath), which then finds all matching elements.

By default, if no context is specified, $() looks for DOM elements within the context of the current HTML document. If you do specify a context, such as a DOM element or jQuery object, the expression will be matched against the contents of that context.

See DOM/Traversing/Selectors for the allowed CSS/XPath syntax for expressions.

Return value: jQuery
Parameters:

  • expr (String): An expression to search with
  • context (Element|jQuery): (optional) A DOM Element, Document or jQuery to use as context

Example:

Finds all p elements that are children of a div element.

$("div > p")

Before:

<p>one</p> <div><p>two</p></div> <p>three</p>

Result:

[ <p>two</p> ]

Example:

Searches for all inputs of type radio within the first form in the document

$("input:radio", document.forms[0])

Example:

This finds all div elements within the specified XML document.

 $("div", xml.responseXML)


$(fn)

$(fn)
$(fn)

$(document).ready()的简写方式，允许你绑定一个在DOM文档载入完成后执行的函数。这个函数的作用如同$(document).ready()一样，只不过用这个函数时，需要把页面中所有其他的$()操作符都包装到其中来。从技术上来说，这个函数是可链接的－－但真正以这种方式链接的情况并不多。你可以在一个页面中使用任意多个$(document).ready事件。

要详细了解ready事件，见ready(Function)。

返回值:jQuery

参数:

  • fn (Function): 当DOM载入完成后要执行的函数

示例:

当DOM就绪可用时，执行其中的函数。

jQuery 代码:

$(function(){ // DOM文档已经载入就绪 });

$( fn )

A shorthand for $(document).ready(), allowing you to bind a function to be executed when the DOM document has finished loading. This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready to be operated on. While this function is, technically, chainable - there really isn't much use for chaining against it.

You can have as many $(document).ready events on your page as you like.

See ready(Function) for details about the ready event.

Return value: jQuery
Parameters:

  • fn (Function): The function to execute when the DOM is ready.

Example:

Executes the function when the DOM is ready to be used.

 $(function(){     // Document is ready   });

Example:

Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.

 jQuery(function($) {     // Your code using failsafe $ alias here...   });


$(html)

$(html)
$(html)

根据提供的原始HTML标记字符串，动态创建由jQuery对象包装的DOM元素。

返回值:jQuery

参数:

  • html (String): 用于动态创建DOM元素的HTML标记字符串
示例1:

动态创建一个div元素（以及其中的所有内容），并将它追加到ID值为body的元素中。在这个函数的内部，是通过临时创建一个元素，并将这个元素的innerHTML属性设置为给定的标记字符串，来实现标记到DOM元素转换的。所以，这个函数既有灵活性，也有局限性。

jQuery 代码:

$("<div><p>Hello</p></div>").appendTo("#body")

$( html )

Create DOM elements on-the-fly from the provided String of raw HTML.

Return value: jQuery
Parameters:

  • html (String): A string of HTML to create on the fly.

Example:

Creates a div element (and all of its contents) dynamically, and appends it to the body element. Internally, an element is created and its innerHTML property set to the given markup. It is therefore both quite flexible and limited.

 $("<div><p>Hello</p></div>").appendTo("body")


$.extend(prop)

$.extend(prop)
$.extend(prop)

扩展jQuery对象。可以用于把函数添加到jQuery名称空间中，以及添加插件方法（插件）。

返回值：Object

参数：

  • prop (Object): 要合并到jQuery对象中的对象
示例：

添加两个插件方法。

jQuery 代码:

jQuery.fn.extend({
  check: function() {
    return   this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return   this.each(function() { this.checked = false; });
  }
});
$("input[@type=checkbox]").check();
$("input[@type=radio]").uncheck();
示例：

向jQuery名称空间中添加两个函数。

jQuery 代码:

 jQuery.extend({
     min: function(a, b) { return a < b?? a?: b; },
     max: function(a, b) { return a > b?? a?: b; }
  });
$.fn.extend( prop )

Extends the jQuery object itself. Can be used to add functions into the jQuery namespace and to add plugin methods (plugins).

Return value: Object
Parameters:

  • prop (Object): The object that will be merged into the jQuery object

Example:

Adds two plugin methods.

 jQuery.fn.extend({
   check: function() {
      return this.each(function() { this.checked = true; });
     },
    uncheck: function() {
      return this.each(function() { this.checked = false; });
     }
   });
   $("input[@type=checkbox]").check();
   $("input[@type=radio]").uncheck();

Example:

Adds two functions into the jQuery namespace

 jQuery.extend({
     min: function(a, b) { return a < b?? a?: b; },
     max: function(a, b) { return a > b?? a?: b; }
  });


$.noConflict()

$.noConflict()
$.noConflict()

运行这个函数将变量$的控制权让渡给第一个实现它的那个库。这样可以确保jQuery不会与其他库的$对象发生冲突。

在运行这个函数后，就只能使用iQuery变量访问iQuery对象。例如，在要用到$("div p")的地方，就必须换成iQuery("div p")。

返回值：undefined

示例 ：

将$引用的对象映射回原始的对象，让渡变量$

jQuery 代码:

jQuery.noConflict();
// 开始使用jQuery
jQuery("div   p").hide();
// 使用其他库的 $()
$("content").style.display = 'none';
示例：

恢复使用别名$，然后创建并执行一个函数，在这个函数的作用域中仍然将$作为jQuery的别名来使用。在这个函数中，原来的$对象是无效的。这个函数对于大多数不依赖于其他库的插件都十分有效。

jQuery 代码:

jQuery.noConflict();
(function($) {
  $(function() {
    //   使用 $ 作为 jQuery 别名的代码
 });
})(jQuery);
// 使用 $ 作为别名的其他库的代码
$.noConflict()

Run this function to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the $ object of other libraries.

By using this function, you will only be able to access jQuery using the 'jQuery' variable. For example, where you used to do $("div p"), you now must do jQuery("div p").

Return value: undefined

Example:

Maps the original object that was referenced by $ back to $

jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';

Example:

Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.

 jQuery.noConflict();
  (function($) {
      $(function() {
       // more code using $ as alias to jQuery
    });
   })(jQuery);
   // other code using $ as an alias to the other library


each(fn)

each(fn)

each(fn)

以每一个匹配的元素作为上下文来执行一个函数。这意味着，每次执行传递进来的函数时，函数中的this关键字都指向一个不同的元素（每次都是一个不同的匹配元素）。

而且，在每次执行函数时，都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数。

返回值：jQuery

参数：

  • fn (Function): 要执行的函数
示例：

迭代两个图像，并设置它们的src属性。

HTML 代码:

<img/><img/>

jQuery 代码:

$("img").each(function(i){ this.src = "test" + i + ".jpg"; });

结果:

<img src="test0.jpg"/><img src="test1.jpg"/>

each( fn )

Execute a function within the context of every matched element. This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific DOM element.

Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set (integer, zero-index).

Return value: jQuery
Parameters:

  • fn (Function): A function to execute

Example:

Iterates over two images and sets their src property

 $("img").each(function(i){     this.src = "test" + i + ".jpg";   });
Before:
 <img/><img/>
Result:
 <img src="test0.jpg"/><img src="test1.jpg"/>

If you want to have the jquery element instead of the dom element, uses the $(this) function. eg.

$("img").each(function(i){
    $(this).toggleClass("example");
    //of course, that's more useful when you have something more complex to do than just toggling a class?;)
  });


eq(pos)

eq(pos)
eq(pos)

将匹配的元素集合缩减为一个元素。这个元素在匹配元素集合中的位置变为0，而集合长度变成1。

返回值：jQuery

参数：

  • pos (Number): 要保留的元素的索引

示例：

$("p").eq(1)

HTML 代码:

<p>This is just a test.</p><p>So is this</p>

结果:

[ <p>So is this</p> ]

eq( pos )

Reduce the set of matched elements to a single element. The position of the element in the set of matched elements starts at 0 and goes to length - 1.

Return value: jQuery
Parameters:

  • pos (Number): The index of the element that you wish to limit to.

Example:

 $("p").eq(1)
Before:
 <p>This is just a test.</p><p>So is this</p>
Result:
 [ <p>So is this</p> ]


get(num)

get(num)
get(num)

取得其中一个匹配的元素。 num表示取得第几个匹配的元素。

返回值:Element

参数:

  • num (Number): 取得第num个位置上的元素
示例:

选择文档中所有的图像，并返回第一个。

HTML 代码:

<img src="test1.jpg"/> <img src="test2.jpg"/>

jQuery 代码:

$("img").get(0);

结果:

[ <img src="test1.jpg"/> ]

get( num )

Access a single matched DOM element at a specified index in the matched set. This allows you to extract the actual DOM element and operate on it directly without necessarily using jQuery functionality on it.

Return value: Element
Parameters:

  • num (Number): Access the element in the Nth position.

Example:

Selects all images in the document and returns the first one

 $("img").get(0);
Before:
 <img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
 <img src="test1.jpg"/>


get()

get()
get()

取得所有匹配的（DOM）元素集合。

这是取得所有匹配元素的一种向后兼容的方式（不同于jQuery对象，而实际上两者都是元素数组）。

返回值：Array<Element>

示例：

选择文档中的所有图像，并返回相应的DOM元素数组。

HTML 代码:

<img src="test1.jpg"/> <img src="test2.jpg"/>

jQuery 代码:

$("img").get();

结果:

[ <img src="test1.jpg"/> <img src="test2.jpg"/> ]

get()

Access all matched DOM elements. This serves as a backwards-compatible way of accessing all matched elements (other than the jQuery object itself, which is, in fact, an array of elements).

It is useful if you need to operate on the DOM elements themselves instead of using built-in jQuery functions.

Return value: Array<Element>

Example:

Selects all images in the document and returns the DOM Elements as an Array

 $("img").get();
Before:
 <img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
 [ <img src="test1.jpg"/> <img src="test2.jpg"/> ]

The reverse function to obtain a jquery object from a dom element is

$(domElement)


gt(pos)

gt(pos)
gt(pos)

将匹配的元素集合缩减为给定位置之后的所有元素。这个元素在匹配元素集合中的位置变为0，而长度变成1。

返回值:jQuery

参数:

  • pos (Number): 把集合缩减为这个位置之后的所有元素

示例:

$("p").gt(0)

HTML 代码:

<p>This is just a test.</p><p>So is this</p>

结果:

[ <p>So is this</p> ]

gt( pos )

Reduce the set of matched elements to all elements after a given position. The position of the element in the set of matched elements starts at 0 and goes to length - 1.

Return value: jQuery
Parameters:

  • pos (Number): Reduce the set to all elements after this position.

Example:

 $("p").gt(0)
Before:
 <p>This is just a test.</p><p>So is this</p>
Result:
 [ <p>So is this</p> ]


index(subject)

index(subject)
index(subject)

搜索与参数表示的对象匹配的元素，并返回相应元素的索引值。

如果找到了匹配的元素，从0开始返回；如果没有找到匹配的元素，返回-1。

返回值:Number

参数

  • subject (Element): 要搜索的对象
示例:

返回ID值为foobar的元素的索引值。

HTML 代码:

<div id="foobar"></div><b></b><span id="foo"></span>

jQuery 代码:

$("").index( $('#foobar')[0] )

结果:

0

示例：

返回ID值为foo的元素的索引值。

HTML 代码:

<div id="foobar"></div><b></b><span id="foo"></span>

jQuery 代码:

$("").index( $('#foo'))

结果:

2

示例：

因为没有ID值为bar的元素，所以返回 -1。

HTML 代码:

<div id="foobar"></div><b></b><span id="foo"></span>

jQuery 代码:

$("*").index( $('#bar'))

结果:

-1

index( subject )

Searches every matched element for the object and returns the index of the element, if found, starting with zero. Returns -1 if the object wasn't found.

Return value: Number
Parameters:

  • subject (Element): Object to search for

Example:

Returns the index for the element with ID foobar

 $("*").index( $('#foobar')[0] )
Before:
 <div id="foobar"><b></b><span id="foo"></span></div>
Result:
 0

Example:

Returns the index for the element with ID foo within another element

 $("*").index( $('#foo')[0] )
Before:
 <div id="foobar"><b></b><span id="foo"></span></div>
Result:
 2

Example:

Returns -1, as there is no element with ID bar

 $("*").index( $('#bar')[0] )
Before:
 <div id="foobar"><b></b><span id="foo"></span></div>
Result:
 -1


length

length
length

当前匹配的元素数量。

返回值：Number

示例：

$("img").length;

HTML 代码:

<img src="test1.jpg"/> <img src="test2.jpg"/>

结果:

2

length

The number of elements currently matched. The size function will return the same value.

Return value: Number

Example:

 $("img").length;
Before:
 <img src="test1.jpg"/> <img src="test2.jpg"/>

Result:

 2


lt(pos)

lt(pos)
lt(pos)

将匹配的元素集合缩减为给定位置之前的所有元素。这个元素在匹配元素集合中的位置变为0，而长度变成1。

返回值：jQuery

参数：

  • pos (Number): 把集合缩减为这个位置之下的所有元素

示例：

$("p").lt(1)

HTML 代码:

<p>This is just a test.</p><p>So is this</p>

结果:

[ <p>This is just a test.</p> ]

lt( pos )

Reduce the set of matched elements to all elements before a given position. The position of the element in the set of matched elements starts at 0 and goes to length - 1.

Return value: jQuery
Parameters:

  • pos (Number): Reduce the set to all elements below this position.

Example:

 $("p").lt(1)
Before:
 <p>This is just a test.</p><p>So is this</p>

Result:

 [ <p>This is just a test.</p> ]


size()

size()
size()

当前匹配的元素数量。

返回值：Number

示例：

$("img").size();

HTML 代码:

<img src="test1.jpg"/> <img src="test2.jpg"/>

结果:

2

size()

Get the number of elements currently matched. This returns the same number as the 'length' property of the jQuery object.

Return value: Number

Example:

 $("img").size();
Before:
 <img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
 2


css

css

通过jQuery内的CSS样式操作方法，可以访问或设置DOM元素的级联样式

String css(String Name) 访问第一个匹配元素的样式属性。

jQuery css(Map properties) 把一个“名/值对”对象设置为所有匹配元素的样式属性。

jQuery css(String key,String|Number value ) 在所有匹配的元素中，设置一个样式属性的值。

String height() 取得第一个匹配元素当前计算的高度值（px）。

jQuery height(String|Number value) 为每个匹配的元素设置CSS高度(width)的值。

String width() 取得第一个匹配元素当前计算的宽度值（px）。

jQuery width(String|Number value) 为每个匹配的元素设置CSS宽度(width)的值。


css(key, value)

css(key, value)
css(key, value)

在所有匹配的元素中，设置一个样式属性的值。

返回值:jQuery

参数:

  • key (String): 要设置的样式属性名称
  • value (Object): 要设置的样式属性的值
示例:

把所有段落的color样式属性值改为红色。

$("p").css("color","red");

HTML 代码:

<p>Test Paragraph.</p>

结果:

<p style="color:red;">Test Paragraph.</p>

示例:

把所有段落的left样式属性值设置为"30px"

$("p").css("left",30);

HTML 代码:

<p>Test Paragraph.</p>

结果:

<p style="left:30px;">Test Paragraph.</p>

css( key, value )

Set a single style property to a value, on all matched elements. If a number is provided, it is automatically converted into a pixel value.

Return value: jQuery
Parameters:

  • key (String): The name of the property to set.
  • value (String|Number): The value to set the property to.

Example:

Changes the color of all paragraphs to red

 $("p").css("color","red");
Before:
 <p>Test Paragraph.</p>

Result:

 <p style="color:red;">Test Paragraph.</p>

Example:

Changes the left of all paragraphs to "30px"

 $("p").css("left",30);
Before:
 <p>Test Paragraph.</p>
Result:
 <p style="left:30px;">Test Paragraph.</p>


css(name)

css(name)
css(name)

访问第一个匹配元素的样式属性。使用这个方法可以很容易地取得第一个匹配元素的样式属性的值。

返回值:String

参数:

  • name (String): 要访问的属性名称

示例:

取得第一个段落的color样式属性的值。

$("p").css("color");

HTML 代码:

<p style="color:red;">Test Paragraph.</p>

结果:

"red"

示例:

取得第一个段落的font-weight样式属性的值。

$("p").css("font-weight");

HTML 代码:

<p style="font-weight: bold;">Test Paragraph.</p>

结果:

"bold"

css( name )

Access a style property on the first matched element. This method makes it easy to retrieve a style property value from the first matched element.

Return value: String
Parameters:

  • name (String): The name of the property to access.

Example:

Retrieves the color style of the first paragraph

 $("p").css("color");
Before:
 <p style="color:red;">Test Paragraph.</p>

Result:

 "red"

Example:

Retrieves the font-weight style of the first paragraph.

 $("p").css("font-weight");
Before:
 <p style="font-weight: bold;">Test Paragraph.</p>
Result:
 "bold"


css(properties)

css(properties)
css(properties)

把一个“名/值对”对象设置为所有匹配元素的样式属性。 这是一种在所有匹配的元素上设置大量样式属性的最佳方式。

返回值:jQuery

参数:

  • properties (Map): 要设置为样式属性的名/值对对象
示例:

为所有p元素设置color和background样式属性。

$("p").css({ color: "red", background: "blue" });

HTML 代码:

<p>Test Paragraph.</p>

结果:

<p style="color:red; background:blue;">Test Paragraph.</p>

css( properties )

Set a key/value object as style properties to all matched elements.

This serves as the best way to set a large number of style properties on all matched elements.

Return value: jQuery
Parameters:

  • properties (Map): Key/value pairs to set as style properties.

Example:

Sets color and background styles to all p elements.

 $("p").css({ color: "red", background: "blue" });

Before:

 <p>Test Paragraph.</p>
Result:
 <p style="color:red; background:blue


height(val)

height(val)

height(val)

为每个匹配的元素设置CSS高度(width)属性的值。如果没有明确指定单位（如：em或%），使用px。

返回值:jQuery

参数:

  • val (String|Number): 要设置的高度值

示例:

$("p").height(20);

HTML 代码:

<p>This is just a test.</p>

结果:

<p style="height:20px;">This is just a test.</p>

示例:

$("p").height("20em");

HTML 代码:

<p>This is just a test.</p>

结果:

<p style="height:20em;">This is just a test.</p>

height( val )

Set the CSS height of every matched element. If no explicit unit was specified (like 'em' or '%') then "px" is added to the width.

Return value: jQuery
Parameters:

  • val (String|Number): Set the CSS property to the specified value.

Example:

 $("p").height(20);

Before:

 <p>This is just a test.</p>
Result:
 <p style="height:20px;">This is just a test.</p>

Example:

 $("p").height("20em");

Before:

 <p>This is just a test.</p>
Result:
 <p style="height:20em;">This is just a test.</p>


height

height
height()

取得第一个匹配元素当前计算的高度值（px）。

返回值:String

示例:

$("p").height();

HTML 代码:

<p>This is just a test.</p>

结果:

300

height()

Get the current computed, pixel, height of the first matched element.

Return value: String
Example:

 $("p").height();

Before:

 <p>This is just a test.</p>
Result:
 300


width(val)

width(val)
width(val)

为每个匹配的元素设置CSS宽度(width)属性的值。如果没有明确指定单位（如：em或%），使用px。

返回值:jQuery

参数:

  • val (String|Number): 要设置的宽度值

示例:

$("p").width(20);

HTML 代码:

<p>This is just a test.</p>

结果:

<p style="width:20px;">This is just a test.</p>

示例:

$("p").width("20em");

HTML 代码:

<p>This is just a test.</p>

结果:

<p style="width:20em;">This is just a test.</p>

width( val )

Set the CSS width of every matched element. If no explicit unit was specified (like 'em' or '%') then "px" is added to the width.

Return value: jQuery
Parameters:

  • val (String|Number): Set the CSS property to the specified value.

Example:

 $("p").width(20);

Before:

 <p>This is just a test.</p>
Result:
 <p style="width:20px;">This is just a test.</p>

Example:

 $("p").width("20em");
Before:
 <p>This is just a test.</p>

Result:

 <p style="width:20em;">This is just a test.</p>


width

width
width()

取得第一个匹配元素当前计算的宽度值（px）。

返回值:String

示例:

$("p").width();

HTML 代码:

<p>This is just a test.</p>

结果:

300

width()

Get the current computed, pixel, width of the first matched element.

Return value: String
Example:

 $("p").width();
Before:
 <p>This is just a test.</p>
Result:
 300


DOM

DOM

Attributes

jQuery addClass(String class) 为每个匹配的元素添加指定的类名

Object attr(String name) 取得第一个匹配元素的属性值。

jQuery attr(Map properties) 将一个“名/值”形式的对象设置为所有匹配元素的属性。

jQuery attr(String key,String|Number value) 为所有匹配的元素设置一个属性值。

jQuery attr(String key,Function value) 为所有匹配的元素设置一个计算的属性值。

String html() 取得第一个匹配元素的html内容

jQuery html(String val) 设置每一个匹配元素的html内容。

jQuery removeAttr(String name ) 从每一个匹配的元素中删除一个属性。

jQuery removeClass(String class) 从所有匹配的元素中删除全部或者指定的类。

String text() 取得所有匹配元素的内容。

String text(String val) 设置所有匹配元素的文本内容。

jQuery toggleClass(String class) 如果存在（不存在）就删除（添加）一个类。

String val() 获得第一个匹配元素的当前值。

jQuery val(String val) 设置每一个匹配元素的值。

Manipulation

jQuery after(<Content> content) 在每个匹配的元素之后插入内容。

jQuery append(<Content> content) 向每个匹配的元素内部追加内容。

jQuery appendTo(<Content> content) 把所有匹配的元素追加到另一个、指定的元素元素集合中。

jQuery before(<Content> content) 在每个匹配的元素之前插入内容。

jQuery clone(Boolean deep) 克隆匹配的DOM元素并且选中这些克隆的副本。

jQuery empty() 删除匹配的元素集合中所有的子节点。

jQuery insertAfter(<Content> content) 把所有匹配的元素插入到另一个、指定的元素元素集合的后面。

jQuery insertBefore(<Content> content) 把所有匹配的元素插入到另一个、指定的元素元素集合的前面。

jQuery prepend(<Content> content) 向每个匹配的元素内部前置内容。

jQuery prependTo(<Content> content) 把所有匹配的元素前置到另一个、指定的元素元素集合中。

jQuery remove(String expr) 从DOM中删除所有匹配的元素。

jQuery wrap(String html) 把所有匹配的元素用其他元素的结构化标记包装起来。

jQuery wrap(Element el) 把所有匹配的元素用其他元素的结构化标记包装起来。

Traversing

jQuery add(String expr) 把与表达式匹配的元素添加到jQuery对象中。

jQuery add(String html) 向匹配的元素集合中添加更多动态创建的元素。

jQuery add(Element|Array<Element> elements) 把一个或多个DOM元素添加到匹配的元素集合中。

jQuery children(String expr) 取得一个包含匹配的元素集合中每一个元素的所有唯一子元素的元素集合。

jQuery contains(String str) 把元素集合筛选为包含指定文本（区分大小写）的元素。

jQuery end() 结束最近的“破坏性”操作，把匹配的元素列表回复到前一个状态。

jQuery filter(String expr) 从匹配的元素集合中删除那些不符合指定的筛选条件的元素（即返回与指定表达式匹配的元素集合）。

jQuery filter(Function filter) 从所有匹配的元素集合中删除那些与指定的表达式（可以是多个）不匹配的元素（即返回与指定表达式匹配的元素集合）。

jQuery find(String expr) 搜索所有与指定表达式匹配的元素。

Boolean is(String expr) 用一个表达式来检查当前选择的元素集合，如果其中至少有一个元素符合这个给定的表达式就返回true。

jQuery next(String expr) 取得一个包含匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。

jQuery not(Element el) 从匹配的元素集合中删除指定的元素。

jQuery not(String expr) 从匹配的元素集合中删除与指定的表达式匹配的元素。

jQuery not(jQuery elems) 从匹配的元素集合中删除所有符合条件的元素集合。

jQuery parent(String expr) 取得一个包含着所有匹配元素的唯一父元素的元素集合。

jQuery parents(String expr) 取得一个包含着所有匹配元素的唯一祖先元素的元素集合（不包含根元素）。

jQuery prev(String expr) 取得一个包含匹配的元素集合中每一个元素紧邻的前一个同辈元素的元素集合。

jQuery siblings(String expr) 取得一个包含匹配的元素集合中每一个元素的所有唯一同辈元素的元素集合。


addClass

addClass
addClass(class)

为每个匹配的元素添加指定的类名。

返回值:jQuery

参数:

  • class (String): 要添加到元素中的CSS类名

示例:

$("p").addClass("selected")

HTML 代码:

<p>Hello</p>

结果:

[ <p class="selected">Hello</p> ]

addClass( class )

Adds the specified class(es) to each of the set of matched elements.

Return value: jQuery
Parameters:

  • class (String): One or more CSS classes to add to the elements

Example:

 $("p").addClass("selected")
Before:
 <p>Hello</p>
Result:
 [ <p class="selected">Hello</p> ]

Example:

 $("p").addClass("selected highlight")
Before:
 <p>Hello</p>
Result:
 [ <p class="selected highlight">Hello</p> ]


attr(key, fn)

attr(key,fn)

attr(key, fn)

为所有匹配的元素设置一个计算的属性值。

不提供值，而是提供一个函数，由这个函数计算的值作为属性值。

返回值:jQuery

参数:

  • key (String): 要设置的属性名称
  • value (Function): 返回值的函数

[示例]:

把src属性的值设置为title属性的值。

$("img").attr("title", function() { return this.src });
HTML标记:
<img src="test.jpg" />
结果:
<img src="test.jpg" title="test.jpg" />
attr( key, fn )

Set a single property to a computed value, on all matched elements.

Instead of supplying a string value as described above, a function is provided that computes the value.

Return value: jQuery
Parameters:

  • key (String): The name of the property to set.
  • value (Function): A function returning the value to set. Scope: Current element, argument: Index of current element

Example:

Sets title attribute from src attribute.

 $("img").attr("title", function() { return this.src });
Before:
 <img src="test.jpg" />
Result:
 <img src="test.jpg" title="test.jpg" />

Example:

Enumerate title attribute.

 $("img").attr("title", function(index) {
   return this.title + (++index);
 });
Before:
 <img title="pic" /><img title="pic" /><img title="pic" />
Result:
 <img title="pic1" /><img title="pic2" /><img title="pic3" />


attr(key, value)

attr(key, value)

attr(key, value)

为所有匹配的元素设置一个属性值。

可以是由${规则}表达式提供的计算值，见示例2。

注意，不能在IE中设置input元素的name属性。可以使用$(html)或.append(html)或.html(html)动态地创建包含name属性的input元素。

返回值:jQuery

参数:

  • key (String): 要设置的属性名称
  • value (Object): 设置属性的值
[示例]:

为所有图像设置src属性。

$("img").attr("src","test.jpg");
HTML标记:
<img/>
结果:
<img src="test.jpg"/>
[示例]:

以src属性的值作为title属性的值。使用了attr(String,Function)的简写方式。

$("img").attr("title", "${this.src}");
HTML标记:
<img src="test.jpg" />
结果:
<img src="test.jpg" title="test.jpg" />
attr( key, value)

Set a single property to a value, on all matched elements.

Note that you can't set the name property of input elements in IE. Use $(html) or .append(html) or .html(html) to create elements on the fly including the name property.

Return value: jQuery
Parameters:

  • key (String): The name of the property to set.
  • value (Object): The value to set the property to.

Example:

Sets src attribute to all images.

 $("img").attr("src","test.jpg");

Before:

 <img/>
Result:
 <img src="test.jpg"/>


attr

attr
attr(name)

取得第一个匹配元素的属性值。通过这个方法可以方便地从第一个匹配元素中获取一个属性的值。

返回值:Object

参数:

  • name (String): 属性名称
示例:

返回文档中第一个图像的src属性值。

$("img").attr("src");

HTML 代码:

<img src="test.jpg"/>

结果:

test.jpg

attr( name )

Access a property on the first matched element. This method makes it easy to retrieve a property value from the first matched element.

If the element does not have an attribute with such a name, undefined is returned.

Return value: Object
Parameters:

  • name (String): The name of the property to access.

Example:

Returns the src attribute from the first image in the document.

 $("img").attr("src");
Before:
 <img src="test.jpg"/>
Result:
 test.jpg


attr(properties)

attr(properties)
attr(properties)

将一个“名/值”形式的对象设置为所有匹配元素的属性。 这是一种在所有匹配元素中批量设置很多属性的最佳方式。

返回值:jQuery

参数:

  • properties (Map): 作为属性的“名/值对”对象

示例:

为所有图像设置src和alt属性。

$("img").attr({ src: "test.jpg", alt: "Test Image" });

HTML 代码:

<img/>

结果:

<img src="test.jpg" alt="Test Image"/>

attr( properties )

Set a key/value object as properties to all matched elements.

This serves as the best way to set a large number of properties on all matched elements.

Return value: jQuery
Parameters:

  • properties (Map): Key/value pairs to set as object properties.

Example:

Sets src and alt attributes to all images.

 $("img").attr({ src: "test.jpg", alt: "Test Image" });
Before:
 <img/>
Result:
 <img src="test.jpg" alt="Test Image"/>


html(val)

html(val)
html(val)

设置每一个匹配元素的html内容。这个函数不能用于XML文档。

返回值:jQuery

参数:

  • val (String): Set the html contents to the specified value.
示例:

$("div").html("<b>new stuff</b>");

HTML 代码:

<div><input/></div>

结果:

<div><b>new stuff</b></div>

html( val )

Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).

Return value: jQuery
Parameters:

  • val (String): Set the html contents to the specified value.

Example:

 $("div").html("<b>new stuff</b>");
Before:
 <div><input/></div>
Result:
 <div><b>new stuff</b></div>


html

html

html()

取得第一个匹配元素的html内容。这个函数不能用于XML文档。

返回值:String

示例:

$("div").html();

HTML 代码:

<div><input/></div>

结果:

<input/>

html()

Get the html contents of the first matched element. This property is not available on XML documents (although it will work for XHTML documents).

Return value: String
Example:

 $("div").html();
Before:
 <div><input/></div>

Result:

 <input/>


removeAttr

removeAttr
removeAttr(name)

从每一个匹配的元素中删除一个属性。

返回值:jQuery

参数:

  • name (String): 要删除的属性名

示例:

$("input").removeAttr("disabled")

HTML 代码:

<input disabled="disabled"/>

结果:

<input/>

removeAttr( name )

Remove an attribute from each of the matched elements.

Return value: jQuery
Parameters:

  • name (String): The name of the attribute to remove.

Example:

 $("input").removeAttr("disabled")
Before:
 <input disabled="disabled"/>
Result:
 <input/>


removeClass

removeClass
removeClass(class)

从所有匹配的元素中删除全部或者指定的类。

返回值:jQuery

参数:

  • class (String): (可选) 要删除的类名

示例:

$("p").removeClass()

HTML 代码:

<p class="selected">Hello</p>

结果:

[ <p>Hello</p> ]

示例:

$("p").removeClass("selected")

HTML 代码:

<p class="selected first">Hello</p>

结果:

[ <p class="first">Hello</p> ]

removeClass( class )

Removes all or the specified class(es) from the set of matched elements.

Return value: jQuery
Parameters:

  • class (String): (optional) One or more CSS classes to remove from the elements

Example:

 $("p").removeClass()

Before:

 <p class="selected">Hello</p>
Result:
 [ <p>Hello</p> ]

Example:

 $("p").removeClass("selected")
Before:
 <p class="selected first">Hello</p>
Result:
 [ <p class="first">Hello</p> ]

Example:

 $("p").removeClass("selected highlight")

Before:

 <p class="highlight selected first">Hello</p>
Result:
 [ <p class="first">Hello</p> ]


text(val)

text(val)
text(val)

设置所有匹配元素的文本内容。这个函数与html()函数具有同样的效果。

返回值:String

参数:

  • val (String): 文本内容
示例:

设置所有段落的文本内容。

$("p").text("Some new text.");

HTML 代码:

<p>Test Paragraph.</p>

结果:

<p>Some new text.</p>

text( val )

Set the text contents of all matched elements.

Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities).

Return value: String
Parameters:

  • val (String): The text value to set the contents of the element to.

Example:

Sets the text of all paragraphs.

 $("p").text("<b>Some</b> new text.");
Before:
 <p>Test Paragraph.</p>
Result:
 <p><b>Some</b> new text.</p>

Example:

Sets the text of all paragraphs.

 $("p").text("<b>Some</b> new text.", true);
Before:
 <p>Test Paragraph.</p>
Result:
 <p><b>Some</b> new text.</p>


text

text
text()

取得所有匹配元素的内容。结果是由所有匹配元素包含的文本内容组合起来的文本。这个方法对HTML和XML文档都有效。

返回值:String

示例:

取得所有段落中文本内容的组合。

$("p").text();

HTML 代码:

<p><b>Test</b> Paragraph.</p><p>Paraparagraph</p>

结果:

Test Paragraph.Paraparagraph

text()

Get the text contents of all matched elements. The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents.

Return value: String
Example:

Gets the concatenated text of all paragraphs

 $("p").text();

Before:

 <p><b>Test</b> Paragraph.</p><p>Paraparagraph</p>
Result:
 Test Paragraph.Paraparagraph


toggleClass

toggleClass
toggleClass(class)

如果存在（不存在）就删除（添加）一个类。

返回值:jQuery

参数:

  • class (String): CSS类名

示例:

$("p").toggleClass("selected")

HTML 代码:

<p>Hello</p><p class="selected">Hello Again</p>

结果:

[ <p class="selected">Hello</p>, <p>Hello Again</p> ]

toggleClass( class )

Adds the specified class if it is not present, removes it if it is present.

Return value: jQuery
Parameters:

  • class (String): A CSS class with which to toggle the elements

Example:

 $("p").toggleClass("selected")
Before:
 <p>Hello</p><p class="selected">Hello Again</p>
Result:
 [ <p class="selected">Hello</p>, <p>Hello Again</p> ]


val(val)

val(val)
val(val)

设置每一个匹配元素的值。

返回值:jQuery

参数:

  • val (String): 要设置的值。

示例:

$("input").val("test");

HTML 代码:

<input type="text" value="some text"/>

结果:

<input type="text" value="test"/>

val( val )

Set the value attribute of every matched element.

Return value: jQuery
Parameters:

  • val (String): Set the property to the specified value.

Example:

 $("input").val("test");
Before:
 <input type="text" value="some text"/>
Result:
 <input type="text" value="test"/>


val

val
val()

获得第一个匹配元素的当前值。

返回值:String

示例:

$("input").val();

HTML 代码:

<input type="text" value="some text"/>

结果:

"some text"

val()

Get the content of the value attribute of the first matched element.

Use caution when relying on this function to check the value of multiple-select elements and checkboxes in a form. While it will still work as intended, it may not accurately represent the value the server will receive because these elements may send an array of values. For more robust handling of field values, see the fieldValue function of the Form Plugin.

Return value: String
Example:

 $("input").val();
Before:
 <input type="text" value="some text"/>
Result:
 "some text"


after

after

after(content)

在每个匹配的元素之后插入内容。

返回值:jQuery

参数:

  • content (<Content>): 插入到每个目标后的内容
示例:

在所有段落之后插入一些HTML标记代码。

$("p").after("<b>Hello</b>");

HTML 代码:

<p>I would like to say: </p>

结果:

<p>I would like to say:   </p><b>Hello</b>
示例:

在所有段落之后插入一个元素。

$("p").after( $("#foo")[0] );

HTML 代码:

<b id="foo">Hello</b><p>I would like to   say: </p>

结果:

<p>I would like to say: </p><b   id="foo">Hello</b>
示例:

在所有段落中后插入一个jQuery对象(类似于一个DOM元素数组)。

$("p").after( $("b") );

HTML 代码:

<b>Hello</b><p>I would like to say:   </p>

结果:

<p>I would like to say:   </p><b>Hello</b>
after( content )

Insert content after each of the matched elements.

Return value: jQuery
Parameters:

  • content (<Content>): Content to insert after each target.

Example:

Inserts some HTML after all paragraphs.

 $("p").after("<b>Hello</b>");
Before:
 <p>I would like to say: </p>
Result:
 <p>I would like to say: </p><b>Hello</b>

Example:

Inserts an Element after all paragraphs.

 $("p").after( $("#foo")[0] );
Before:
 <b id="foo">Hello</b><p>I would like to say: </p>
Result:
 <p>I would like to say: </p><b id="foo">Hello</b>

Example:

Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs.

 $("p").after( $("b") );
Before:
 <b>Hello</b><p>I would like to say: </p>
Result:
 <p>I would like to say: </p><b>Hello</b>


append

append
append(content)

向每个匹配的元素内部追加内容。 这个操作与对指定的元素执行appendChild方法，将它们添加到文档中的情况类似。

返回值:jQuery

参数:

  • content (<Content>): 要追加到目标中的内容
示例:

向所有段落中追加一些HTML标记。

$("p").append("<b>Hello</b>");

HTML 代码:

<p>I would like to say: </p>

结果:

<p>I would like to say:   <b>Hello</b></p>
示例:

向所有段落中追加一个元素。

$("p").append( $("#foo")[0] );

HTML 代码:

<p>I would like to say: </p><b   id="foo">Hello</b>

结果:

<p>I would like to say: <b   id="foo">Hello</b></p>
示例:

向所有段落中追加一个jQuery对象(类似于一个DOM元素数组)。

$("p").append( $("b") );

HTML 代码:

<p>I would like to say:   </p><b>Hello</b>

结果:

<p>I would like to say:   <b>Hello</b></p>
append( content )

Append content to the inside of every matched element.

This operation is similar to doing an appendChild to all the specified elements, adding them into the document.

Return value: jQuery
Parameters:

  • content (<Content>): Content to append to the target

Example:

Appends some HTML to all paragraphs.
$("p").append("<b>Hello</b>");

Before:

<p>I would like to say: </p>

After:

<p>I would like to say: <b>Hello</b></p>

Example:

Appends an Element to all paragraphs.

$("p").append( $("#foo")[0] );

Before:

<p>I would like to say: </p><b id="foo">Hello</b>

After:

<p>I would like to say: <b id="foo">Hello</b></p>

Example:

Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.

$("p").append( $("b") );

Before:

<p>I would like to say: </p><b>Hello</b>

After:

<p>I would like to say: <b>Hello</b></p>


appendTo(expr)

appendTo(expr)
appendTo(expr)

把所有匹配的元素追加到另一个、指定的元素元素集合中。实际上，使用这个方法是颠倒了常规的$(A).append(B)的操作，即不是把B追加到A中，而是把A追加到B中。

返回值:jQuery

参数:

  • expr (String): 用于匹配元素的jQuery表达式

示例:

把所有段落追加到ID值为foo的元素中。

$("p").appendTo("#foo");

HTML 代码:

<p>I would like to say: </p><div   id="foo"></div>

结果:

<div id="foo"><p>I would like to say:   </p></div>
appendTo( content )

Append all of the matched elements to another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).append(B), in that instead of appending B to A, you're appending A to B.

Return value: jQuery
Parameters:

  • content (<Content>): Content to append to the selected element to.

Example:

Appends all paragraphs to the element with the ID "foo"

 $("p").appendTo("#foo");
Before:
 <p>I would like to say: </p><div id="foo"></div>
Result:
 <div id="foo"><p>I would like to say: </p></div>


before

before
before(content)

在每个匹配的元素之前插入内容。

返回值:jQuery

参数:

  • content (<Content>): 插入到每个目标前的内容
示例:

在所有段落之前插入一些HTML标记代码。

$("p").before("<b>Hello</b>");

HTML 代码:

<p>I would like to say: </p>

结果:

<b>Hello</b><p>I would like to say:   </p>
示例:

在所有段落之前插入一个元素。

$("p").before( $("#foo")[0] );

HTML 代码:

<p>I would like to say: </p><b   id="foo">Hello</b>

结果:

<b id="foo">Hello</b><p>I would like to say:   </p>
示例:

在所有段落中前插入一个jQuery对象(类似于一个DOM元素数组)。

$("p").before( $("b") );

HTML 代码:

<p>I would like to say:   </p><b>Hello</b>

结果:

<b>Hello</b><p>I would like to say:   </p>
before( content )

Insert content before each of the matched elements.

Return value: jQuery
Parameters:

  • content (<Content>): Content to insert before each target.

Example:

Inserts some HTML before all paragraphs.

 $("p").before("<b>Hello</b>");
Before:
 <p>I would like to say: </p>
Result:
 <b>Hello</b><p>I would like to say: </p>

Example:

Inserts an Element before all paragraphs.

 $("p").before( $("#foo")[0] );

Before:

 <p>I would like to say: </p><b id="foo">Hello</b>

Result:

 <b id="foo">Hello</b><p>I would

Example:

Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.

 $("p").before( $("b") );
Before:
 <p>I would like to say: </p><b>Hello</b>
Result:
 <b>Hello</b><p>I would like to say


clone

clone
clone(deep)

克隆匹配的DOM元素并且选中这些克隆的副本。 在想把DOM文档中元素的副本添加到其他位置时这个函数非常有用。

返回值:jQuery

参数:

  • deep (Boolean): (可选)如果除了元素本身不想克隆其任何后代节点设置为false
示例:

克隆所有b元素（并选中这些克隆的副本），然后将它们前置到所有段落中。

$("b").clone().prependTo("p");

HTML 代码:

<b>Hello   <span>world</span></b><p>, how are you?</p>

结果:

<b>Hello   <span>world</span></b><p>Hello   <span>world</span></b>, how are you?</p>

clone( deep )

Clone matched DOM Elements and select the clones.

This is useful for moving copies of the elements to another location in the DOM.

Return value: jQuery
Parameters:

  • deep (Boolean): (Optional) Set to false if you don't want to clone all descendant nodes, in addition to the element itself.

Example:

Clones all b elements (and selects the clones) and prepends them to all paragraphs.

 $("b").clone().prependTo("p");
Before:
 <b>Hello</b><p>, how are you?</p>
Result:
 <b>Hello</b><p><b>Hello</b>, how are you?</p>


empty()

empty()
empty()

删除匹配的元素集合中所有的子节点。

返回值:jQuery

示例:

$("p").empty()

HTML 代码:

<p>Hello, <span>Person</span> <a   href="#">and person</a></p>

结果:

[ <p></p> ]

empty()

Removes all child nodes from the set of matched elements.

Return value: jQuery
Example:

 $("p").empty()
Before:
 <p>Hello, <span>Person</span> <a href="#">and person</a></p>
Result:
 [ <p></p> ]


insertAfter(expr)

insertAfter(expr)
insertAfter(expr)

把所有匹配的元素插入到另一个、指定的元素元素集合的后面。

实际上，使用这个方法是颠倒了常规的$(A).after(B)的操作，即不是把B插入到A后面，而是把A插入到B后面。

返回值:jQuery

参数:

  • expr (String): 用于匹配元素的jQuery表达式

示例:

与 $("#foo").after("p")相同

$("p").insertAfter("#foo");

HTML 代码:

<p>I would like to say: </p><div   id="foo">Hello</div>

结果:

<div id="foo">Hello</div><p>I would like to   say: </p>
insertAfter( content )

Insert all of the matched elements after another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).after(B), in that instead of inserting B after A, you're inserting A after B.

Return value: jQuery
Parameters:

  • content (<Content>): Content to insert the selected element after.

Example:

Same as $("#foo").after("p")

 $("p").insertAfter("#foo");
Before:
 <p>I would like to say: </p><div id="foo">Hello</div>

Result:

 <div id="foo">Hello</div><p>I would like to say: </p>


insertBefore(expr)

insertBefore(expr)
insertBefore(expr)

把所有匹配的元素插入到另一个、指定的元素元素集合的前面。

实际上，使用这个方法是颠倒了常规的$(A).before(B)的操作，即不是把B插入到A前面，而是把A插入到B前面。

返回值:jQuery

参数:

  • expr (String): 用于匹配元素的jQuery表达式

示例:

与 $("#foo").before("p")相同

$("p").insertBefore("#foo");

HTML 代码:

<div id="foo">Hello</div><p>I would   like to say: </p>

结果:

<p>I would like to say: </p><div   id="foo">Hello</div>

insertBefore( content )

Insert all of the matched elements before another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).before(B), in that instead of inserting B before A, you're inserting A before B.

Return value: jQuery
Parameters:

  • content (<Content>): Content to insert the selected element before.

Example:

Same as $("#foo").before("p")

 $("p").insertBefore("#foo");
Before:
 <div id="foo">Hello</div><p>I would like to say: </p>
Result:
 <p>I would like to say: </p><div id="foo">Hello</div>


prepend(content)

prepend(content)
prepend(content)

向每个匹配的元素内部前置内容。 这是向所有匹配元素内部的开始处插入内容的最佳方式。

返回值:jQuery

参数:

  • content (<Content>): 要插入到目标元素内部前端的内容
示例:

向所有段落中前置一些HTML标记代码。

$("p").prepend("<b>Hello</b>");

HTML 代码:

<p>I would like to say: </p>

结果:

<p><b>Hello</b>I would like to say: </p>

示例:

向所有段落中前置一个元素。

$("p").prepend( $("#foo")[0] );

HTML 代码:

<p>I would like to say: </p><b id="foo">Hello</b>

结果:

<p><b id="foo">Hello</b>I would like to say: </p>

示例:

向所有段落中前置一个jQuery对象(类似于一个DOM元素数组)。

$("p").prepend( $("b") );

HTML 代码:

<p>I would like to say: </p><b>Hello</b>

结果:

<p><b>Hello</b>I would like to say: </p>

prepend( content )

Prepend content to the inside of every matched element.

This operation is the best way to insert elements inside, at the beginning, of all matched elements.

Return value: jQuery
Parameters:

  • content (<Content>): Content to prepend to the target.

Example:

Prepends some HTML to all paragraphs.

 $("p").prepend("<b>Hello</b>");

Before:

 <p>I would like to say: </p>

Result:

 <p><b>Hello</b>I would like to say: </p>

Example:

Prepends an Element to all paragraphs.

 $("p").prepend( $(".foo")[0] );
Before:
 <p>I would like to say: </p>
   <p>I would like to say: </p>
  <b class="foo">Hello</b>
   <b class="foo">Good By</b>
Result:
 <p><b class="foo">Hello</b>I would like to say: </p>
   <p><b class="foo">Hello</b>I would like to say: </p>

(note the [0], that indicates that we only prepend the first element of $(".foo"))

Example:

Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.

 $("p").prepend( $("b") );
Before:
 <p>I would like to say: </p><b>Hello</b>
Result:
 <p><b>Hello</b>I would like to say: </p>


prependTo(expr)

prependTo(expr)
prependTo(expr)

把所有匹配的元素前置到另一个、指定的元素元素集合中。

实际上，使用这个方法是颠倒了常规的$(A).prepend(B)的操作，即不是把B前置到A中，而是把A前置到B中。

返回值:jQuery

参数:

  • expr (String): 用于匹配元素的jQuery表达式
示例:

把所有段落前置到ID值为foo的元素中。

$("p").prependTo("#foo");

HTML 代码:

<p>I would like to say: </p><div id="foo"><b>Hello</b></div>

结果:

<div id="foo"><p>I would like to say: </p><b>Hello</b></div>

prependTo( content )

Prepend all of the matched elements to another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).prepend(B), in that instead of prepending B to A, you're prepending A to B.

Return value: jQuery
Parameters:

  • content (<Content>): Content to prepend to the selected element to.

Example:

Prepends all paragraphs to the element with the ID "foo"

 $("p").prependTo("#foo");
Before:
 <p>I would like to say: </p><div id="foo"><b>Hello</b></div>
Result:
 <div id="foo"><p>I would like to say: </p><b>Hello</b></div>


remove(expr)

remove(expr)
remove(expr)

从DOM中删除所有匹配的元素。

这个方法不会把匹配的元素从jQuery对象中删除，因而可以在将来再使用这些匹配的元素。 可以通过一个可选的表达式对要删除的元素进行筛选。

返回值:jQuery

参数:

  • expr (String): (可选)用于筛选元素的jQuery表达式

示例:

$("p").remove();

HTML 代码:

<p>Hello</p> how are <p>you?</p>

结果:

how are

示例:

$("p").remove(".hello");

HTML 代码:

<p class="hello">Hello</p> how are <p>you?</p>

结果:

how are <p>you?</p>

remove( expr )

Removes all matched elements from the DOM. This does NOT remove them from the jQuery object, allowing you to use the matched elements further.

Can be filtered with an optional expressions.

Return value: jQuery
Parameters:

  • expr (String): (optional) A jQuery expression to filter elements by.

Example:

 $("p").remove();

Before:

 <p>Hello</p> how are <p>you?</p>
Result:
 how are

Example:

 $("p").remove(".hello");
Before:
 <p class="hello">Hello</p> how are <p>you?</p>
Result:
 how are <p>you?</p>


wrap(elem)

wrap(elem)
wrap(elem)

把所有匹配的元素用其他元素的结构化标记包装起来。

这种包装对于在文档中插入额外的结构化标记最有用，而且它不会破坏原始文档的语义品质。

这个函数的原理是检查提供的第一个元素并在它的代码结构中找到最上层的祖先元素－－这个祖先元素就是包装元素。 当HTML标记代码中的元素包含文本时无法使用这个函数。

因此，如果要添加文本应该在包装完成之后再行添加。

返回值:jQuery

参数:

  • elem (Element): 用于包装目标元素的DOM元素

示例:

$("p").wrap( document.getElementById('content') );

HTML 代码:

<p>Test Paragraph.</p><div id="content"></div>

结果:

<div id="content"><p>Test Paragraph.</p></div>

wrap( elem )

Wrap all matched elements with a structure of other elements. This wrapping process is most useful for injecting additional stucture into a document, without ruining the original semantic qualities of a document.

This works by going through the first element provided and finding the deepest ancestor element within its structure - it is that element that will en-wrap everything else.

This does not work with elements that contain text. Any necessary text must be added after the wrapping is done.

Return value: jQuery
Parameters:

  • elem (Element): A DOM element that will be wrapped around the target.

Example:

 $("p").wrap( document.getElementById('content') );
Before:
 <p>Test Paragraph.</p><div id="content"></div>
Result:
 <div id="content"><p>Test Paragraph.</p></div>


wrap(elem)

wrap(elem)

wrap(html)

把所有匹配的元素用其他元素的结构化标记包装起来。

这种包装对于在文档中插入额外的结构化标记最有用，而且它不会破坏原始文档的语义品质。

这个函数的原理是检查提供的第一个元素（它是由所提供的HTML标记代码动态生成的），并在它的代码结构中找到最上层的祖先元素－－这个祖先元素就是包装元素。

当HTML标记代码中的元素包含文本时无法使用这个函数。因此，如果要添加文本应该在包装完成之后再行添加。

返回值:jQuery

参数:

  • html (String): HTML标记代码字符串，用于动态生成元素并包装目标元素

示例:

$("p").wrap("<div class='wrap'></div>");

HTML 代码:

<p>Test Paragraph.</p>

结果:

<div class='wrap'><p>Test Paragraph.</p></div>

wrap( html )

Wrap all matched elements with a structure of other elements. This wrapping process is most useful for injecting additional stucture into a document, without ruining the original semantic qualities of a document.

This works by going through the first element provided (which is generated, on the fly, from the provided HTML) and finds the deepest ancestor element within its structure - it is that element that will en-wrap everything else.

This does not work with elements that contain text. Any necessary text must be added after the wrapping is done.

Return value: jQuery
Parameters:

  • html (String): A string of HTML, that will be created on the fly and wrapped around the target.

Example:

 $("p").wrap("<div class='wrap'></div>");
Before:
 <p>Test Paragraph.</p>
Result:
 <div class='wrap'><p>Test Paragraph


add(elements)

add(elements)

add(elements)

把一个或多个DOM元素添加到匹配的元素集合中。 这个函数用于把一个DOM元素集合添加到一个jQuery对象中。

返回值:jQuery

参数:

  • elements (Element|Array<Element>): 要添加的一个或多个DOM元素

示例:

$("p").add( document.getElementById("a") )

HTML 代码:

<p>Hello</p><p><span id="a">Hello Again</span></p>

结果:

[ <p>Hello</p>, <p><span id="a">Hello   Again</span></p>, <span id="a">Hello Again</span>   ]

示例：

$("p").add([document.getElementById("a"),   document.getElementById("b")])

HTML 代码:

<p>Hello</p><p><span id="a">Hello Again</span><span id="b">And Again</span></p>

结果:

[ <p>Hello</p>, <p><span id="a">Hello   Again</span><span id="b">And Again</span></p>,
 <span   id="a">Hello Again</span>, <span id="b">And Again</span>   ]

add( elements )

Adds one or more Elements to the set of matched elements.

Return value: jQuery
Parameters:

  • elements (Element|Array<Element>): One or more Elements to add

Example:

 $("p").add( document.getElementById("a") )
Before:
 <p>Hello</p><p><span id="a">Hello Again</span></p>
Result:
 [ <p>Hello</p>, <span id="a">Hello Again</span> ]

Example:

 $("p").add( document.forms[0].elements )
Before:
 <p>Hello</p><p><form><input/><button/></form>
Result:
 [ <p>Hello</p>, <input/>, <button/> ]


add(html)

add(html)
add(html)

向匹配的元素集合中添加更多动态创建的元素。

返回值:jQuery

参数:

  • html (String): 动态创建元素的HTML代码字符串

示例:

$("p").add("<span>Again</span>")

HTML 代码:

<p>Hello</p>

结果:

[ <p>Hello</p>, <span>Again</span> ]

add( html )

Adds more elements, created on the fly, to the set of matched elements.

Return value: jQuery
Parameters:

  • html (String): A string of HTML to create on the fly.

Example:

 $("p").add("<span>Again</span>")
Before:
 <p>Hello</p>
Result:
 [ <p>Hello</p>, <span>Again</span> ]


add(expr)

add(expr)
add(expr)

把与表达式匹配的元素添加到jQuery对象中。这个函数可以用于连接分别与两个表达式匹配的元素结果集。

返回值:jQuery

参数:

  • expr (String): 用于匹配相加结果元素的表达式

示例:

$("p").add("span")

HTML 代码:

<p>Hello</p><p><span>Hello Again</span></p>

结果:

[ <p>Hello</p>, <p><span>Hello Again</span></p>, <span>Hello Again</span> ]

add( expr )

Adds more elements, matched by the given expression, to the set of matched elements.

Return value: jQuery
Parameters:

  • expr (String): An expression whose matched elements are added

Example:

Compare the above result to the result of $('p'), which would just result in [ <p>Hello</p> ]. Using add(), matched elements of $('span') are simply added to the returned jQuery-object.

 $("p").add("span")
Before:
 (HTML) <p>Hello</p><span>Hello Again</span>

Result:

 (jQuery object matching 2 elements) [ <p>Hello</p>, <span>Hello Again</span> ]


children(expr)

children(expr)
children(expr)

取得一个包含匹配的元素集合中每一个元素的所有唯一子元素的元素集合。 可以用可选的表达式进行筛选。

返回值:jQuery

参数:

  • expr (String): (可选) 用于筛选子元素的表达式
示例:

找到每个div的所有子元素。

$("div").children()

HTML 代码:

<p>Hello</p><div><span>Hello   Again</span></div><p>And Again</p>

结果:

[ <span>Hello Again</span> ]
示例:

找到每个div的所有子元素中带有类名为selected的元素。

$("div").children(".selected")

HTML 代码:

<div><span>Hello</span><p   class="selected">Hello Again</p><p>And   Again</p></div>

结果:

[ <p class="selected">Hello Again</p> ]

children( expr )

Get a set of elements containing all of the unique children of each of the matched set of elements.

This set can be filtered with an optional expression that will cause only elements matching the selector to be collected.

Return value: jQuery
Parameters:

  • expr (String): (optional) An expression to filter the child Elements with

Example:

Find all children of each div.

 $("div").children()
Before:
 <p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
Result:
 [ <span>Hello Again</span> ]

Example:

Find all children with a class "selected" of each div.

 $("div").children(".selected")
Before:
 <div><span>Hello</span><p class="selected">Hello Again</p><p>And Again</p></div>
Result:
 [ <p class="selected">Hello Again</p> ]


contains(str)

contains(str)
contains(str)

把元素集合筛选为包含指定文本（区分大小写）的元素。

返回值:jQuery

参数:

  • str (String): 包含在元素中的文本

示例:

$("p").contains("test")

HTML 代码:

<p>This is just a test.</p><p>So is   this</p>

结果:

[ <p>This is just a test.</p> ]
contains( str )

Filter the set of elements to those that contain the specified text.

Return value: jQuery
Parameters:

  • str (String): The string that will be contained within the text of an element.

Example:

 $("p").contains("test")
Before:
 <p>This is just a test.</p><p>So is this</p>
Result:
 [ <p>This is just a test.</p> ]


end()

end()
end()

结束最近的“破坏性”操作，把匹配的元素列表回复到前一个状态。在调用end函数后，匹配的元素列表会回复到上一个操作之前的匹配元素列表状态。

如果前面的操作（对元素列表的状态）没有破坏性，则什么也不改变。

返回值:jQuery

示例:

选择所有段落，并在它们中查找span元素，然后恢回复到选择所有段落的状态。

$("p").find("span").end();

HTML 代码:

<p><span>Hello</span>, how are   you?</p>

结果:

[ <p>...</p> ]
end()

Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state (right before the destructive operation).

If there was no destructive operation before, an empty set is returned.

A 'destructive' operation is any operation that changes the set of matched jQuery elements. These functions are: add, children, clone, filter, find, not, next, parent, parents, prev and siblings.

Return value: jQuery
Example:

Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.

 $("p").find("span").end();

Before:

 <p><span>Hello</span>, how are you?</p>
Result:
 [ <p>...</p> ]


filter(filter)

filter(filter)

filter(filter)

从匹配的元素集合中删除那些不符合指定的筛选条件的元素（即返回与指定表达式匹配的元素集合）。这个方法用于缩小搜索的范围。

返回值:jQuery

参数:

  • filter (Function): 作为筛选条件的函数
示例:

删除所有拥有一个ol子元素的元素。

$("p").filter(function(index) { return $("ol",   this).length == 0; })

HTML 代码:

<p><ol><li>Hello</li></ol></p><p>How   are you?</p>

结果:

[ <p>How are you?</p> ]

filter( filter )

Removes all elements from the set of matched elements that do not pass the specified filter. This method is used to narrow down the results of a search.

Return value: jQuery
Parameters:

  • filter (Function): A function to use for filtering

Example:

Remove all elements that have a child ol element

 $("p").filter(function(index) {     return $("ol", this).length == 0;   })
Before:
 <p><ol><li>Hello</li></ol></p><p>How are you?</p>
Result:
 [ <p>How are you?</p> ]


filter

filter

filter(expression)

从所有匹配的元素集合中删除那些与指定的表达式（可以是多个）不匹配的元素（即返回与指定表达式匹配的元素集合）。这个方法用于缩小匹配的范围。

使用表达式字符串数组可以实现一次完成多重筛选的效果。

返回值:jQuery

参数:

  • expression (String|Array<String>): 要搜索的表达式（或表达式数组）
示例:

选择所有段落并删除那些类名不是selected的元素。

$("p").filter(".selected")

HTML 代码:

<p class="selected">Hello</p><p>How are   you?</p>

结果:

[ <p class="selected">Hello</p> ]
示例:

选择所有段落并删除那些类名不是selected的元素，但不删除第一个元素。

$("p").filter([".selected", ":first"])

HTML 代码:

<p>Hello</p><p>Hello   Again</p><p class="selected">And Again</p>

结果:

[ <p>Hello</p>, <p class="selected">And   Again</p> ]
filter( expression )

Removes all elements from the set of matched elements that do not match the specified expression(s). This method is used to narrow down the results of a search.

Provide a comma-separated list of expressions to apply multiple filters at once.

Return value: jQuery
Parameters:

  • expression (String): Expression(s) to search with.

Example:

Selects all paragraphs and removes those without a class "selected".

 $("p").filter(".selected")
Before:
 <p class="selected">Hello</p><p>How are you?</p>
Result:
 [ <p class="selected">Hello</p> ]

Example:

Selects all paragraphs and removes those without class "selected" and being the first one.

 $("p").filter(".selected,?:first")
Before:
 <p>Hello</p><p>Hello Again</p><p class="selected">And Again</p>
Result:
 [ <p>Hello</p>, <p class="selected">And Again</p> ]


find(expr)

find(expr)
find(expr)

搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。

所有搜索都依靠jQuery表达式来完成。这个表达式可以使用CSS1-3的选择符语法或基本的XPath语法来写。

返回值:jQuery

参数:

  • expr (String): 用于搜索的表达式
示例:

从所有的段落开始，进一步搜索下面的span元素。与$("p span")相同。

$("p").find("span");

HTML 代码:

<p><span>Hello</span>, how are   you?</p>

结果:

[ <span>Hello</span> ]
find( expr )

Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.

All searching is done using a jQuery expression. The expression can be written using CSS 1-3 Selector syntax, or basic XPath.

Return value: jQuery
Parameters:

  • expr (String): An expression to search with.

Example:

Starts with all paragraphs and searches for descendant span elements, same as $("p span")

 $("p").find("span");
Before:
 <p><span>Hello</span>, how are you?</p>
Result:
 [ <span>Hello</span> ]


is(expr)

is(expr)
is(expr)

用一个表达式来检查当前选择的元素集合，如果其中至少有一个元素符合这个给定的表达式就返回true。

如果没有元素符合这个表达式，或者表达式是无效的，都返回false。

其中的表达式可以使用filter(String)函数，因此filter()函数原有的规则在这里也适用。

返回值:Boolean

参数:

  • expr (String): 用于筛选的表达式
示例:

因为input元素的父元素是一个表单元素，所以返回true。

$("input[@type='checkbox']").parent().is("form")

HTML 代码:

<form><input type="checkbox"   /></form>

结果:

true
示例:

因为input元素的父元素是一个p元素，所以返回false。

$("input[@type='checkbox']").parent().is("form")

HTML 代码:

<form><p><input type="checkbox"   /></p></form>

结果:

false

is( expr )

Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.

Does return false, if no element fits or the expression is not valid.

filter(String) is used internally, therefore all rules that apply there apply here, too.

Return value: Boolean
Parameters:

  • expr (String): The expression with which to filter

Example:

Returns true, because the parent of the input is a form element

 $("input[@type='checkbox']").parent().is("form")
Before:
 <form><input type="checkbox" /></form>
Result:
 true

Example:

Returns false, because the parent of the input is a p element

 $("input[@type='checkbox']").parent().is("form")

Before:

 <form><p><input type="checkbox" /></p></form>
Result:
 false


next(expr)

next(expr)
next(expr)

取得一个包含匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。

这个函数只返回后面那个紧邻的同辈元素，而不是后面所有的同辈元素。 可以用一个可选的表达式进行筛选。

返回值:jQuery

参数:

  • expr (String): (可选) 用于筛选后面同辈元素的表达式
示例:

找到每个段落的后面紧邻的同辈元素。

$("p").next()

HTML 代码:

<p>Hello</p><p>Hello   Again</p><div><span>And Again</span></div>

结果:

[ <p>Hello Again</p>, <div><span>And   Again</span></div> ]
示例:

找到每个段落的后面紧邻的同辈元素中类名为selected的元素。

$("p").next(".selected")

HTML 代码:

<p>Hello</p><p class="selected">Hello   Again</p><div><span>And Again</span></div>

结果:

[ <p class="selected">Hello Again</p>   ]
next( expr )

Get a set of elements containing the unique next siblings of each of the matched set of elements.

It only returns the very next sibling for each element, not all next siblings.

You may provide an optional expression to filter the match.

Return value: jQuery
Parameters:

  • expr (String): (optional) An expression to filter the next Elements with

Example:

Find the very next sibling of each paragraph.

 $("p").next()
Before:
 <p>Hello</p><p>Hello Again</p><div><span>And Again</span></div>
Result:
 [ <p>Hello Again</p>, <div><span>And Again</span></div> ]

Example:

Find the very next sibling of each paragraph that has a class "selected".

 $("p").next(".selected")
Before:
 <p>Hello</p><p class="selected">Hello Again</p><div><span>And Again</span></div>

Result:

 [ <p class="selected">Hello Again</p> ]


not(elems)

not(elems)
not(elems)

从匹配的元素集合中删除所有符合条件的元素集合。这个函数用于从jQuery对象中删除一个或多个元素。

返回值:jQuery

参数:

  • elems (jQuery): 要从匹配的jQuery元素集合中删除的元素集合
示例:

从全部段落的集合中删除所有与“div p.selected”匹配的元素。

$("p").not( $("div p.selected") )

HTML 代码:

<div><p>Hello</p><p   class="selected">Hello Again</p></div>

结果:

[ <p>Hello</p> ]
not( elems )

Removes any elements inside the array of elements from the set of matched elements. This method is used to remove one or more elements from a jQuery object.

Please note: the expression cannot use a reference to the element name. See the two examples below.

Return value: jQuery
Parameters:

  • elems (jQuery): A set of elements to remove from the jQuery set of matched elements.

Example:

Removes all elements that match "div p.selected" from the total set of all paragraphs.

 $("p").not( $("div p.selected") )
Before:
 <div><p>Hello</p><p class="selected">Hello Again</p></div>
Result:
 [ <p>Hello</p> ]


not(expr)

not(expr)
not(expr)

从匹配的元素集合中删除与指定的表达式匹配的元素。这个函数用于从一个jQuery对象中删除一个或多个元素。

返回值:jQuery

参数:

  • expr (String): 用于匹配要删除元素的表达式
示例:

从所有段落中删除ID值为selected的元素。

$("p").not("#selected")

HTML 代码:

<p>Hello</p><p id="selected">Hello   Again</p>

结果:

[ <p>Hello</p> ]
not( expr )

Removes elements matching the specified expression from the set of matched elements. This method is used to remove one or more elements from a jQuery object.

Return value: jQuery
Parameters:

  • expr (String): An expression with which to remove matching elements

Example:

Removes the element with the ID "selected" from the set of all paragraphs.

 $("p").not("#selected")

Before:

 <p>Hello</p><p id="selected">Hello Again</p>
Result:
 [ <p>Hello</p> ]


not

not
not(el)

从匹配的元素集合中删除指定的元素。这个方法用于从一个jQuery对象中删除一个元素。

返回值:jQuery

参数:

  • el (Element): 要删除的元素
示例:

从所有的段落集合中删除ID为selected的元素。

$("p").not( $("#selected")[0] )

HTML 代码:

<p>Hello</p><p id="selected">Hello   Again</p>

结果:

[ <p>Hello</p> ]
not( el )

Removes the specified Element from the set of matched elements. This method is used to remove a single Element from a jQuery object.

Return value: jQuery
Parameters:

  • el (Element): An element to remove from the set

Example:

Removes the element with the ID "selected" from the set of all paragraphs.

 $("p").not( $("#selected")[0] )

Before:

 <p>Hello</p><p id="selected">Hello Again</p>
Result:
 [ <p>Hello</p> ]


parent(expr)

parent(expr)
parent(expr)

取得一个包含着所有匹配元素的唯一父元素的元素集合。 可以通过一个可选的表达式进行筛选。

返回值:jQuery

参数:

  • expr (String): (可选) 用于筛选父元素的表达式
示例:

找到每个段落的父元素。

$("p").parent()

HTML 代码:

<div><p>Hello</p><p>Hello</p></div>

结果:

[   <div><p>Hello</p><p>Hello</p></div> ]
示例:

找到段落的父元素中每个类名为selected的父元素。

$("p").parent(".selected")

HTML 代码:

<div><p>Hello</p></div><div   class="selected"><p>Hello Again</p></div>

结果:

[ <div class="selected"><p>Hello   Again</p></div> ]
parent( expr )

Get a set of elements containing the unique parents of the matched set of elements.

You may use an optional expression to filter the set of parent elements that will match.

Return value: jQuery
Parameters:

  • expr (String): (optional) An expression to filter the parents with

Example:

Find the parent element of each paragraph.

 $("p").parent()
Before:
 <div><p>Hello</p><p>Hello</p></div>
Result:
 [ <div><p>Hello</p><p>Hello</p></div> ]

Example:

Find the parent element of each paragraph with a class "selected".

 $("p").parent(".selected")
Before:
 <div><p>Hello</p></div><div class="selected"><p>Hello Again</p></div>
Result:
 [ <div class="selected"><p>Hello Again</p></div> ]


parents(expr)

parents(expr)
parents(expr)

取得一个包含着所有匹配元素的唯一祖先元素的元素集合（不包含根元素）。 可以通过一个可选的表达式进行筛选。

返回值:jQuery

参数:

  • expr (String): (可选) 用于筛选祖先元素的表达式
示例:

找到每个span元素的父元素。

$("span").parents()

HTML 代码:

<html><body><div><p><span>Hello</span></p><span>Hello   Again</span></div></body></html>

结果:

[ <body>...</body>, <div>...</div>,   <p><span>Hello</span></p> ]
示例:

找到每个span元素的父元素中是p元素的元素。

$("span").parents("p")

HTML 代码:

<html><body><div><p><span>Hello</span></p><span>Hello   Again</span></div></body></html>

结果:

[ <p><span>Hello</span></p>   ]
parents( expr )

Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).

The matched elements can be filtered with an optional expression.

Return value: jQuery
Parameters:

  • expr (String): (optional) An expression to filter the ancestors with

Example:

Find all parent elements of each span.

 $("span").parents()
Before:
 <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>
Result:
 [ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ]

Example:

Find all parent elements of each span that is a paragraph.

 $("span").parents("p")
Before:
 <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>

Result:

 [ <p><span>Hello</span></p> ]


prev(expr)

prev(expr)
prev(expr)

取得一个包含匹配的元素集合中每一个元素紧邻的前一个同辈元素的元素集合。

可以用一个可选的表达式进行筛选。 这个函数只返回前一个紧邻的同辈元素，而不是前面所有的同辈元素。

返回值:jQuery

参数:

  • expr (String): (可选) 用于筛选前一个同辈元素的表达式
示例:

找到每个段落紧邻的前一个同辈元素。

$("p").prev()

HTML 代码:

<p>Hello</p><div><span>Hello   Again</span></div><p>And Again</p>

结果:

[ <div><span>Hello Again</span></div>   ]

示例:

找到每个段落紧邻的前一个同辈元素中类名为selected的元素。

$("p").prev(".selected")

HTML 代码:

<div><span>Hello</span></div><p   class="selected">Hello Again</p><p>And Again</p>

结果:

[ <p class="selected">Hello Again</p>   ]
prev( expr )

Get a set of elements containing the unique previous siblings of each of the matched set of elements.

Use an optional expression to filter the matched set.

Only the immediately previous sibling is returned, not all previous siblings.

Return value: jQuery
Parameters:

  • expr (String): (optional) An expression to filter the previous Elements with

Example:

Find the very previous sibling of each paragraph.

 $("p").prev()
Before:
 <p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
Result:
 [ <div><span>Hello Again</span></div> ]

Example:

Find the very previous sibling of each paragraph that has a class "selected".

 $("p").prev(".selected")

Before:

 <div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>
Result:
 [ <div><span>Hello</span></div> ]


siblings(expr)

siblings(expr)
siblings(expr)

取得一个包含匹配的元素集合中每一个元素的所有唯一同辈元素的元素集合。 可以用可选的表达式进行筛选。

返回值:jQuery

参数:

  • expr (String): (可选) 用于筛选同辈元素的表达式
示例:

找到每个div的所有同辈元素。

$("div").siblings()

HTML 代码:

<p>Hello</p><div><span>Hello   Again</span></div><p>And Again</p>

结果:

[ <p>Hello</p>, <p>And Again</p>   ]
示例:

找到每个div的所有同辈元素中带有类名为selected的元素。

$("div").siblings(".selected")

HTML 代码:

<div><span>Hello</span></div><p   class="selected">Hello Again</p><p>And Again</p>

结果:

[ <p class="selected">Hello Again</p>   ]
siblings( expr )

Get a set of elements containing all of the unique siblings of each of the matched set of elements.

Can be filtered with an optional expressions.

Return value: jQuery
Parameters:

  • expr (String): (optional) An expression to filter the sibling Elements with

Example:

Find all siblings of each div.

 $("div").siblings()
Before:
 <p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
Result:
 [ <p>Hello</p>, <p>And Again</p> ]

Example:

Find all siblings with a class "selected" of each div.

 $("div").siblings(".selected")
Before:
 <div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>

Result:

 [ <p class="selected">Hello Again</p> ]


事件

事件

这一章描述了jQuery API中与事件相关的函数

jQuery bind(String type,Object data,Function fn) 为每一个匹配元素的特定事件（像click）绑定一个事件处理器函数。

jQuery blur() 触发每一个匹配元素的blur事件。

jQuery blur(Function fn) 在每一个匹配元素的blur事件中绑定一个处理函数。

jQuery change(Function fn) 在每一个匹配元素的change事件中绑定一个处理函数。

jQuery click() 触发每一个匹配元素的click事件。这个函数会调用执行绑定到click事件的所有函数。

jQuery click(Function fn) 在每一个匹配元素的click事件中绑定一个处理函数。

jQuery dblclick(Function fn) 在每一个匹配元素的dblclick事件中绑定一个处理函数。

jQuery error(Function fn) 在每一个匹配元素的error事件中绑定一个处理函数。

jQuery focus() 触发每一个匹配元素的focus事件。

jQuery focus(Function fn) 在每一个匹配元素的focus事件中绑定一个处理函数。

jQuery hover(Function over,Function out) 一个模仿悬停事件（鼠标移动到一个对象上面及移出这个对象）的方法.

jQuery keydown(Function fn) 在每一个匹配元素的keydown事件中绑定一个处理函数。

jQuery keypress(Function fn) 在每一个匹配元素的keypress事件中绑定一个处理函数。

jQuery keyup(Function fn) 在每一个匹配元素的keyup事件中绑定一个处理函数。

jQuery load(Function fn) 在每一个匹配元素的load事件中绑定一个处理函数。

jQuery mousedown(Function fn) 在每一个匹配元素的mousedown事件中绑定一个处理函数。

jQuery mousemove(Function fn) 在每一个匹配元素的mousemove事件中绑定一个处理函数。

jQuery mouseout(Function fn) 在每一个匹配元素的mouseout事件中绑定一个处理函数。

jQuery mouseover(Function fn) 在每一个匹配元素的mouseover事件中绑定一个处理函数。

jQuery mouseup(Function fn) 在每一个匹配元素的mouseup事件中绑定一个处理函数。

jQuery one(String type,Object data,Function fn) 为每一个匹配元素的特定事件（像click）绑定一个事件处理器函数（只执行一次）。

jQuery ready(Function fn) 当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。

jQuery resize(Function fn) 在每一个匹配元素的resize事件中绑定一个处理函数。

jQuery scroll(Function fn) 在每一个匹配元素的滚动事件中绑定一个处理函数。

jQuery select() 触发每一个匹配元素的select事件。

jQuery select(Function fn) 在每一个匹配元素的select事件中绑定一个处理函数。

jQuery submit() 触发每一个匹配元素的submit事件。

jQuery submit(Function fn) 在每一个匹配元素的submit事件中绑定一个处理函数。

jQuery toggle(Function even,Function odd) 每次点击时切换要调用的函数。

jQuery trigger(String type,Array data) 在每一个匹配的元素上触发某类事件。

jQuery unbind(String type,Function fn) 反绑定，从每一个匹配的元素中删除绑定的事件

jQuery unload(Function fn) 在每一个匹配元素的unload事件中绑定一个处理函数。


bind(type, data, fn)

bind(type, data, fn)
bind(type,data,fn)

为每一个匹配元素的特定事件（像click）绑定一个事件处理器函数。

这个事件处理函数会接收到一个事件对象，可以通过它来阻止（浏览器）默认的行为。

如果既想取消默认的行为，又想阻止事件起泡，这个事件处理函数必须返回false。 多数情况下，可以把事件处理器函数定义为匿名函数（见示例一）。在不可能定义匿名函数的情况下，可以传递一个可选的数据对象作为第二个参数（而事件处理器函数则作为第三个参数），见示例二。

返回值:jQuery

参数:

  • type (String): 事件类型
  • data (Object): (可选) 作为event.data属性值传递给事件对象的额外数据对象
  • fn (Function): 绑定到每个匹配元素的事件上面的处理函数

示例:

$("p").bind("click", function(){ alert( $(this).text()   ); });

HTML 代码:

<p>Hello</p>

结果:

alert("Hello")
示例:

为事件对象传递一些额外的数据。

function handler(event) {
 alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)

结果:

alert("bar")
示例:

通过返回false来取消默认的行为并阻止事件起泡。

$("form").bind("submit", function() { return false;   })
示例:

通过使用 preventDefault 方法只取消默认的行为。

$("form").bind("submit", function(event){   event.preventDefault(); });
示例:

通过使用 stopPropagation 方法只阻止事件起泡。

$("form").bind("submit", function(event){
   event.stopPropagation();
});
bind( type, data, fn )

Binds a handler to a particular event (like click) for each matched element. The event handler is passed an event object that you can use to prevent default behaviour. To stop both default action and event bubbling, your handler has to return false.

In most cases, you can define your event handlers as anonymous functions (see first example). In cases where that is not possible, you can pass additional data as the second parameter (and the handler function as the third), see second example.

Return value: jQuery
Parameters:

  • type (String): An event type
  • data (Object): (optional) Additional data passed to the event handler as event.data
  • fn (Function): A function to bind to the event on each of the set of matched elements

Example:

 $("p").bind("click", function(){     alert( $(this).text() );   });
Before:
 <p>Hello</p>
Result:
 alert("Hello")

Example:

Pass some additional data to the event handler.

 function handler(event) {
     alert(event.data.foo);
 }
 $("p").bind("click", {foo: "bar"}, handler)
Result:
 alert("bar")

Example:

Cancel a default action and prevent it from bubbling by returning false from your function.

 $("form").bind("submit", function() { return false; })

Example:

Cancel only the default action by using the preventDefault method.

 $("form").bind("submit", function(event){
     event.preventDefault();
 });


blur(fn)

blur(fn)

blur(fn)

在每一个匹配元素的blur事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的blur事件中绑定的处理函数。

示例:

$("p").blur( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onblur="alert('Hello');">Hello</p>

blur(fn)

Bind a function to the blur event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the blur event on each of the matched elements.

Example:

 $("p").blur( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onblur="alert('Hello');">Hello</p>


blur

blur
blur()

触发每一个匹配元素的blur事件。这个函数会调用执行绑定到blur事件的所有函数。

注意：这个函数不会调用相应元素的blur方法！如果需要通过代码来使一个元素获得焦点，必须使用DOM方法，例如：$("#myinput")[0].blur();

返回值:jQuery

示例:

$("p").blur();

HTML 代码:

<p onblur="alert('Hello');">Hello</p>

结果:

alert('Hello');

blur()

Trigger the blur event of each matched element. This causes all of the functions that have been bound to that blur event to be executed, and calls the browser's default blur action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the blur event.

Note: This does not execute the blur method of the underlying elements! If you need to blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();

Return value: jQuery
Example:

 $("p").blur();
Before:
 <p onblur="alert('Hello');">Hello</p>
Result:
 alert('Hello');


change(fn)

change(fn)
change(fn)

在每一个匹配元素的change事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的change事件中绑定的处理函数。
示例:

$("p").change( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onchange="alert('Hello');">Hello</p>

change(fn)

Bind a function to the change event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the change event on each of the matched elements.

Example:

 $("p").change( function() { alert("Hello"); } );

Before:

 <p>Hello</p>
Result:
 <p onchange="alert('Hello');">Hello</p>


click(fn)

click(fn)
click(fn)

在每一个匹配元素的click事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的click事件中绑定的处理函数。

示例:

$("p").click( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onclick="alert('Hello');">Hello</p>

click(fn)

Bind a function to the click event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the click event on each of the matched elements.

Example:

 $("p").click( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onclick="alert('Hello');">Hello</p>


click

click
click()

触发每一个匹配元素的click事件。这个函数会调用执行绑定到click事件的所有函数。

返回值:jQuery

示例:

$("p").click();

HTML 代码:

<p onclick="alert('Hello');">Hello</p>

结果:

alert('Hello');

click()

Trigger the click event of each matched element. This causes all of the functions that have been bound to that click event to be executed.

Return value: jQuery
Example:

 $("p").click();
Before:
 <p onclick="alert('Hello');">Hello</p>
Result:
 alert('Hello');


dblclick(fn)

dblclick(fn)
dblclick(fn)

在每一个匹配元素的dblclick事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的dblclick事件中绑定的处理函数。
示例:

$("p").dblclick( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p ondblclick="alert('Hello');">Hello</p>

dblclick(fn)

Bind a function to the dblclick event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the dblclick event on each of the matched elements.

Example:

 $("p").dblclick( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p ondblclick="alert('Hello');">Hello</p>


error(fn)

error(fn)
error(fn)

在每一个匹配元素的error事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的error事件中绑定的处理函数。

示例:

$("p").error( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onerror="alert('Hello');">Hello</p>

error(fn)

Bind a function to the error event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the error event on each of the matched elements.

Example:

 $("p").error( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onerror="alert('Hello');">Hello</p>


focus(fn)

focus(fn)
focus(fn)

在每一个匹配元素的focus事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的submit事件中绑定的处理函数。

示例:

$("p").focus( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onfocus="alert('Hello');">Hello</p>

focus(fn)

Bind a function to the focus event of each matched element.

Return value: jQuery
Parameters:
  • fn (Function): A function to bind to the focus event on each of the matched elements.

Example:

 $("p").focus( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onfocus="alert('Hello');">Hello</p>


focus

focus
focus()

触发每一个匹配元素的focus事件。这个函数会调用执行绑定到focus事件的所有函数。

注意：这个函数不会调用相应元素的focus方法！如果需要通过代码来使一个元素获得焦点，必须使用DOM方法，例如：$("#myinput")[0].focus();

返回值:jQuery

示例:

$("p").focus();

HTML 代码:

<p onfocus="alert('Hello');">Hello</p>

结果:

alert('Hello');

focus()

Trigger the focus event of each matched element. This causes all of the functions that have been bound to thet focus event to be executed.

Note: This does not execute the focus method of the underlying elements! If you need to focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();

Return value: jQuery
Example:

 $("p").focus();
Before:
 <p onfocus="alert('Hello');">Hello</p>
Result:
 alert('Hello');


hover(over, out)

hover(over, out)
hover(over,out)

一个模仿悬停事件（鼠标移动到一个对象上面及移出这个对象）的方法。

这是一个自定义的方法，它为频繁使用的任务提供了一种“保持在其中”的状态。 当鼠标移动到一个匹配的元素上面时，会触发指定的第一个函数。当鼠标移出这个元素时，会触发指定的第二个函数。

而且，会伴随着对鼠标是否仍然处在特定元素中的检测（例如，处在div中的图像），如果是，则会继续保持“悬停”状态，而不触发移出事件（修正了使用mouseout事件的一个常见错误）。

返回值:jQuery

参数:

  • over (Function): 鼠标移到元素上要触发的函数
  • out (Function): 鼠标移出元素要触发的函数

示例:

$("p").hover(function(){
  $(this).addClass("over");
},
function(){
 $(this).addClass("out");
});
?hover(over, out)

A method for simulating hovering (moving the mouse on, and off, an object). This is a custom method which provides an 'in' to a frequent task.

Whenever the mouse cursor is moved over a matched element, the first specified function is fired. Whenever the mouse moves off of the element, the second specified function fires. Additionally, checks are in place to see if the mouse is still within the specified element itself (for example, an image inside of a div), and if it is, it will continue to 'hover', and not move out (a common error in using a mouseout event handler).

Return value: jQuery
Parameters:

  • over (Function): The function to fire whenever the mouse is moved over a matched element.
  • out (Function): The function to fire whenever the mouse is moved off of a matched element.

Example:

 $("p").hover(function(){
     $(this).addClass("hover");
 },function(){
     $(this).removeClass("hover");
 });


keydown(fn)

keydown(fn)
keydown(fn)

在每一个匹配元素的keydown事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的keydown事件中绑定的处理函数。

示例:

$("p").keydown( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onkeydown="alert('Hello');">Hello</p>

keydown(fn)

Bind a function to the keydown event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the keydown event on each of the matched elements.

Example:

 $("p").keydown( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onkeydown="alert('Hello');">Hello</p>


keypress(fn)

keypress(fn)
keypress(fn)

在每一个匹配元素的keypress事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的keypress事件中绑定的处理函数。

示例:

$("p").keypress( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onkeypress="alert('Hello');">Hello</p>

keypress(fn)

Bind a function to the keypress event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the keypress event on each of the matched elements.

Example:

 $("p").keypress( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onkeypress="alert('Hello');">Hello</p>


keyup(fn)

keyup(fn)
keyup(fn)

在每一个匹配元素的keyup事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的keyup事件中绑定的处理函数。

示例:

$("p").keyup( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onkeyup="alert('Hello');">Hello</p>

keyup(fn)

Bind a function to the keyup event of each matched element.

Return value:jQuery
Parameters:

  • fn (Function): A function to bind to the keyup event on each of the matched elements.

Example:

 $("p").keyup( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onkeyup="alert('Hello');">Hello</p>


load(fn)

load(fn)
load(fn)

在每一个匹配元素的load事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的load事件中绑定的处理函数。

示例:

$("p").load( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onload="alert('Hello');">Hello</p>

load(fn)

Bind a function to the load event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the load event on each of the matched elements.

Example:

 $("p").load( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onload="alert('Hello');">Hello</p>


mousedown(fn)

mousedown(fn)

mousedown(fn)

在每一个匹配元素的mousedown事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的mousedown事件中绑定的处理函数。
示例:

$("p").mousedown( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onmousedown="alert('Hello');">Hello</p>

mousedown(fn)

Bind a function to the mousedown event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the mousedown event on each of the matched elements.

Example:

 $("p").mousedown( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onmousedown="alert('Hello');">Hello</p>


mousemove(fn)

mousemove(fn)
mousemove(fn)

在每一个匹配元素的mousemove事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的mousemove事件中绑定的处理函数。

示例:

$("p").mousemove( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onmousemove="alert('Hello');">Hello</p>

mousemove( fn )

Bind a function to the mousemove event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the mousemove event on each of the matched elements.

Example:

 $("p").mousemove( function() { alert("Hello"); } );

Before:

 <p>Hello</p>
Result:
 <p onmousemove="alert('Hello');">Hello</p>


mouseout(fn)

mouseout(fn)
mouseout(fn)

在每一个匹配元素的mouseout事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的mouseout事件中绑定的处理函数。

示例:

$("p").mouseout( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onmouseout="alert('Hello');">Hello</p>

mouseout(fn)

Bind a function to the mouseout event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the mouseout event on each of the matched elements.

Example:

 $("p").mouseout( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onmouseout="alert('Hello');">Hello</p>


mouseover(fn)

mouseover(fn)
mouseover(fn)

在每一个匹配元素的mouseover事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的mouseover事件中绑定的处理函数。

示例:

$("p").mouseover( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onmouseover="alert('Hello');">Hello</p>

mouseover(fn)

Bind a function to the mouseover event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the mousedown event on each of the matched elements.

Example:

 $("p").mouseover( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onmouseover="alert('Hello');">Hello</p>


mouseup(fn)

mouseup(fn)
mouseup(fn)

在每一个匹配元素的mouseup事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的mouseup事件中绑定的处理函数。

示例:

$("p").mouseup( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onmouseup="alert('Hello');">Hello</p>

mouseup(fn)

Bind a function to the mouseup event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the mouseup event on each of the matched elements.

Example:

 $("p").mouseup( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onmouseup="alert('Hello');">Hello</p>


one(type, data, fn)

one(type, data, fn)

one(type,data,fn)

为每一个匹配元素的特定事件（像click）绑定一个事件处理器函数。

在每个对象上，这个事件处理函数只会被执行一次。其他规则与bind()函数相同。

这个事件处理函数会接收到一个事件对象，可以通过它来阻止（浏览器）默认的行为。如果既想取消默认的行为，又想阻止事件起泡，这个事件处理函数必须返回false。 多数情况下，可以把事件处理器函数定义为匿名函数（见示例一）。

在不可能定义匿名函数的情况下，可以传递一个可选的数据对象作为第二个参数（而事件处理器函数则作为第三个参数），见示例二。

返回值:jQuery

参数:

  • type (String): 事件类型
  • data (Object): (可选) 作为event.data属性值传递给事件对象的额外数据对象
  • fn (Function): 绑定到每个匹配元素的事件上面的处理函数

示例:

$("p").one("click", function(){
 alert( $(this).text()   );
});

HTML 代码:

<p>Hello</p>

结果:

alert("Hello")

one(type,data,fn)

Binds a handler to a particular event (like click) for each matched element. The handler is executed only once for each element. Otherwise, the same rules as described in bind() apply. The event handler is passed an event object that you can use to prevent default behaviour. To stop both default action and event bubbling, your handler has to return false.

In most cases, you can define your event handlers as anonymous functions (see first example). In cases where that is not possible, you can pass additional data as the second paramter (and the handler function as the third), see second example.

Return value: jQuery
Parameters:

  • type (String): An event type
  • data (Object): (optional) Additional data passed to the event handler as event.data
  • fn (Function): A function to bind to the event on each of the set of matched elements

Example:

 $("p").one("click", function(){
     alert( $(this).text() );
});
Before:
 <p>Hello</p>
Result:
 alert("Hello")


ready(fn)

ready(fn)
ready(fn)

当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。

这是事件模块中最重要的一个函数，因为它可以极大地提高web应用程序的响应速度。 简单地说，这个方法纯粹是对向window.load事件注册事件的替代方法。通过使用这个方法，可以在DOM载入就绪能够读取并操纵时立即调用你所绑定的函数，而99.99%的JavaScript函数都需要在那一刻执行。

有一个参数－－对jQuery函数的引用－－会传递到这个ready事件处理函数中。可以给这个参数任意起一个名字，并因此可以不再担心命名冲突而放心地使用$别名。 请确保在<body>元素的onload事件中没有注册函数，否则不会触发$(document).ready()事件。 可以在同一个页面中无限次地使用$(document).ready()事件。其中注册的函数会按照（代码中的）先后顺序依次执行。

返回值:jQuery

参数:

  • fn (Function): 要在DOM就绪时执行的函数

示例:

$(document).ready(function(){ Your code here... });

示例:

同时使用$(document).ready()和参数来编写应用$别名的具有安全保障（failsafe）的jQuery代码，从而不会依赖于全局别名。

jQuery(function($) {
   // Your code using failsafe $   alias here...
});
ready(fn)

Bind a function to be executed whenever the DOM is ready to be traversed and manipulated. This is probably the most important function included in the event module, as it can greatly improve the response times of your web applications.

In a nutshell, this is a solid replacement for using window.onload, and attaching a function to that. By using this method, your bound function will be called the instant the DOM is ready to be read and manipulated, which is when what 99.99% of all JavaScript code needs to run.

There is one argument passed to the ready event handler: A reference to the jQuery function. You can name that argument whatever you like, and can therefore stick with the $ alias without risk of naming collisions.

Please ensure you have no code in your <body> onload event handler, otherwise $(document).ready() may not fire.

You can have as many $(document).ready events on your page as you like. The functions are then executed in the order they were added.

Return value: jQuery
Parameters:

  • fn (Function): The function to be executed when the DOM is ready.

Example:

 $(document).ready(function(){ Your code here... });

Example:

Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.

 jQuery(function($) {
     // Your code using failsafe $ alias here...
 });


resize(fn)

resize(fn)
resize(fn)

在每一个匹配元素的resize事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的resize事件中绑定的处理函数。

示例:

$("p").resize( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onresize="alert('Hello');">Hello</p>

resize(fn)

Bind a function to the resize event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the resize event on each of the matched elements.

Example:

 $("p").resize( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onresize="alert('Hello');">Hello</p>


scroll(fn)

scroll(fn)
scroll(fn)

在每一个匹配元素的scroll事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的scoll事件中绑定的处理函数

示例:

$("p").scroll( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onscroll="alert('Hello');">Hello</p>

scroll(fn)

Bind a function to the scroll event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the scroll event on each of the matched elements.

Example:

 $("p").scroll( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onscroll="alert('Hello');">Hello</p>


select(fn)

select(fn)
select(fn)

在每一个匹配元素的select事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的select事件中绑定的处理函数。

示例:

$("p").select( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onselect="alert('Hello');">Hello</p>

select(fn)

Bind a function to the select event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the select event on each of the matched elements.

Example:

 $("p").select( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onselect="alert('Hello');">Hello</p>


select

select
select()

触发每一个匹配元素的select事件。这个函数会调用执行绑定到select事件的所有函数。

返回值:jQuery

示例:

$("p").select();

HTML 代码:

<p onselect="alert('Hello');">Hello</p>

结果:

alert('Hello');

select()

Trigger the select event of each matched element. This causes all of the functions that have been bound to that select event to be executed, and calls the browser's default select action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the select event.

Return value: jQuery
Example:

 $("p").select();

Before:

 <p onselect="alert('Hello');">Hello</p>
Result:
 alert('Hello');


submit(fn)

submit(fn)
submit(fn)

在每一个匹配元素的submit事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的submit事件中绑定的处理函数

示例:

如果输入框中没有输入文本，阻止表单提交。

$("#myform").submit( function() {
 return $("input",   this).val().length > 0;
} );

HTML 代码:

<form id="myform"><input /></form>

submit(fn)

Bind a function to the submit event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the submit event on each of the matched elements.

Example:

Prevents the form submission when the input has no value entered.

 $("#myform").submit( function() {
     return $("input", this).val().length > 0;
 } );
Before:
 <form id="myform"><input /></form>


submit

submit
submit()

触发每一个匹配元素的submit事件。这个函数会调用执行绑定到submit事件的所有函数。

注意：这个函数不会调用form元素的submit方法！如果需要通过代码来提交表单，必须使用DOM方法，例如：$("form")[0].submit();

返回值:jQuery

示例:

触发注册到表单的所有submit事件，但不提交表单。

$("form").submit();

submit()

Trigger the submit event of each matched element. This causes all of the functions that have been bound to that submit event to be executed, and calls the browser's default submit action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the submit event.

Note: This does not execute the submit method of the form element! If you need to submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();

Return value: jQuery
Example:

Triggers all submit events registered to the matched form(s), and submits them.

 $("form").submit();


toggle(even, odd)

toggle(even, odd)
toggle(even,odd)

每次点击时切换要调用的函数。

如果点击了一个匹配的元素，则触发指定的第一个函数，当再次点击同一元素时，则触发指定的第二个函数。随后的每次点击都重复对这两个函数的轮番调用。 可以使用unbind("click")来删除。

返回值:jQuery

参数:

  • even (Function): 第奇数次点击时要执行的函数。
  • odd (Function): 第偶数次点击时要执行的函数。

示例:

$("p").toggle(function(){
  $(this).addClass("selected");
},function(){
 $(this).removeClass("selected");
});
toggle(even,odd)

Toggle between two function calls every other click. Whenever a matched element is clicked, the first specified function is fired, when clicked again, the second is fired. All subsequent clicks continue to rotate through the two functions.

Use unbind("click") to remove.

Return value: jQuery
Parameters:

  • even (Function): The function to execute on every even click.
  • odd (Function): The function to execute on every odd click.

Example:

 $("p").toggle(function(){
     $(this).addClass("selected");
 },function(){
     $(this).removeClass("selected");
 });


trigger(type)

trigger(type)
trigger(type)

在每一个匹配的元素上触发某类事件。

返回值:jQuery

参数:

  • type (String): 要触发的事件类型

示例:

$("p").trigger("click")

HTML 代码:

<p click="alert('hello')">Hello</p>

结果:

alert('hello')

trigger(type, data)

Trigger a type of event on every matched element. This will also cause the default action of the browser with the same name (if one exists) to be executed. For example, passing 'submit' to the trigger() function will also cause the browser to submit the form. This default action can be prevented by returning false from one of the functions bound to the event.

You can also trigger custom events registered with bind.

Return value: jQuery
Parameters:

  • type (String): An event type to trigger.
  • data (Array): (optional) Additional data to pass as arguments (after the event object) to the event handler

Example:

 $("p").trigger("click")
Before:
 <p click="alert('hello')">Hello</p>
Result:
 alert('hello')

Example:

Example of how to pass arbitrary data to an event

 $("p").click(function(event, a, b) {
     // when a normal click fires, a and b are undefined
    // for a trigger like below a refers too "foo" and b refers to "bar"
}).trigger("click", ["foo", "bar"]);
Example:
 $("p").bind("myEvent",function(event,message1,message2) {
       alert(message1 + ' ' + message2);
  });
 $("p").trigger("myEvent",["Hello","World"]);
Result:
 alert('Hello World') // One for each paragraph


unbind(type, fn)

unbind(type, fn)
unbind(type,fn)

反绑定，从每一个匹配的元素中删除绑定的事件。

如果没有参数，则删除所有绑定的事件。 如果提供了事件类型作为参数，则只删除该类型的绑定事件。 如果把在绑定时传递的处理函数作为第二个参数，则只有这个特定的事件处理函数会被删除。

返回值:jQuery

参数:

  • type (String): (可选) 事件类型
  • fn (Function): (可选) 要从每个匹配元素的事件中反绑定的事件处理函数

示例:

$("p").unbind()

HTML 代码:

<p onclick="alert('Hello');">Hello</p>

结果:

[ <p>Hello</p> ]

示例:

$("p").unbind( "click" )

HTML 代码:

<p onclick="alert('Hello');">Hello</p>

结果:

[ <p>Hello</p> ]

示例:

$("p").unbind( "click", function() { alert("Hello"); } )

HTML 代码:

<p onclick="alert('Hello');">Hello</p>

结果:

[ <p>Hello</p> ]

unbind(type,fn)

The opposite of bind, removes a bound event from each of the matched elements.

Without any arguments, all bound events are removed.

If the type is provided, all bound events of that type are removed.

If the function that was passed to bind is provided as the second argument, only that specific event handler is removed.

Return value: jQuery
Parameters:

  • type (String): (optional) An event type
  • fn (Function): (optional) A function to unbind from the event on each of the set of matched elements

Example:

 $("p").unbind()
Before:
 <p onclick="alert('Hello');">Hello</p>
Result:
 [ <p>Hello</p> ]

Example:

 $("p").unbind( "click" )
Before:
 <p onclick="alert('Hello');">Hello</p>
Result:
 [ <p>Hello</p> ]

Example:

 $("p").unbind( "click", function() { alert("Hello"); } )
Before:
 <p onclick="alert('Hello');">Hello</p>
Result:
 [ <p>Hello</p> ]


unload(fn)

unload(fn)
unload(fn)

在每一个匹配元素的unload事件中绑定一个处理函数。

返回值:jQuery

参数:

  • fn (Function): 在每一个匹配元素的unload事件中绑定的处理函数。

示例:

$("p").unload( function() { alert("Hello"); } );

HTML 代码:

<p>Hello</p>

结果:

<p onunload="alert('Hello');">Hello</p>

unload(fn)

Bind a function to the unload event of each matched element.

Return value: jQuery
Parameters:

  • fn (Function): A function to bind to the unload event on each of the matched elements.

Example:

 $("p").unload( function() { alert("Hello"); } );
Before:
 <p>Hello</p>
Result:
 <p onunload="alert('Hello');">Hello</p>


Effects

Effects

jQuery animate(Hash params,String|Number speed,String easing,Function callback ) 用于创建自定义动画的函数。

jQuery fadeIn(String|Number speed,Function callback) 通过不透明度的变化来实现所有匹配元素的淡入效果，并在动画完成后可选地触发一个回调函数。

jQuery fadeOut(String|Number speed,Function callback) 通过不透明度的变化来实现所有匹配元素的淡出效果，并在动画完成后可选地触发一个回调函数。

jQuery fadeTo(String|Number speed,Number opacity,Function callback ) 通过不透明度到指定透明度来实现所有匹配元素的淡出效果，并在动画完成后可选地触发一个回调函数。

jQuery hide() 隐藏显示的元素

jQuery hide(String|Number speed,Function callback) 以优雅的动画隐藏所有匹配的元素，并在显示完成后可选地触发一个回调函数。

jQuery show() 显示隐藏的匹配元素。

jQuery show(String|Number speed,Function callback) 以优雅的动画显示所有匹配的元素，并在显示完成后可选地触发一个回调函数。

jQuery slideDown(String|Number speed,Function callback) 通过高度变化（向下增大）来动态地显示所有匹配的元素，在显示完成后可选地触发一个回调函数。

jQuery slideToggle(String|Number speed,Function callback) 通过高度变化来切换所有匹配元素的可见性，并在切换完成后可选地触发一个回调函数。

jQuery slideUp(String|Number speed,Function callback ) 通过高度变化（向上减小）来动态地隐藏所有匹配的元素，在隐藏完成后可选地触发一个回调函数。

jQuery toggle() 切换元素的可见状态。


animate(params, speed, easing, callback)

animate(params, speed, easing, callback)
animate(params,speed,easing,callback)

用于创建自定义动画的函数。这个函数的关键在于指定动画形式及结果样式属性对象。这个对象中每个属性都表示一个可以变化的样式属性（如“height”、“top”或“opacity”）。

而每个属性的值表示这个样式属性到多少时动画结束。如果是一个数值，样式属性就会从当前的值渐变到指定的值。如果使用的是“hide”、“show”或“toggle”这样的字符串值，则会为该属性调用默认的动画形式。

返回值:jQuery

参数:

  • params (Hash): 一组包含作为动画属性和终值的样式属性和及其值的集合
  • speed (String|Number): (可选) 三种预定速度之一的字符串("slow", "normal", or "fast")或表示动画时长的毫秒数值(如：1000)
  • easing (String): (可选) 要使用的擦除效果的名称(需要插件支持).
  • callback (Function): (可选) 在动画完成时执行的函数

示例:

$("p").animate({ height: 'toggle', opacity: 'toggle' },   "slow");

示例:

$("p").animate({ left: 50, opacity: 'show' },   500);
示例:

一个使用“擦除”函数提供不同动画样式的例子。只有在一个插件可以提供这个“擦除”函数（jQuery库中默认只提供“linear”函数）的情况下才有效。

$("p").animate({ opacity: 'show' }, "slow",   "easein");
animate( params, speed, easing, callback )

A function for making your own, custom animations. The key aspect of this function is the object of style properties that will be animated, and to what end. Each key within the object represents a style property that will also be animated (for example: "height", "top", or "opacity").

Note that properties should be specified using camel case eg. marginLeft instead of margin-left.

The value associated with the key represents to what end the property will be animated. If a number is provided as the value, then the style property will be transitioned from its current state to that new number. Otherwise if the string "hide", "show", or "toggle" is provided, a default animation will be constructed for that property.

Return value: jQuery
Parameters:

  • params (Hash): A set of style attributes that you wish to animate, and to what end.
  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • easing (String): (optional) The name of the easing effect that you want to use (Plugin Required).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against. This function is passed a single parameter, the element that was being animated.

Example:

 $("p").animate({     height: 'toggle', opacity: 'toggle'   }, "slow");

Example:

 $("p").animate({     left: 50, opacity: 'show'   }, 500);

Example:

An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function (Only 'linear' is provided by default, with jQuery).

 $("p").animate({     opacity: 'show'   }, "slow", "easein");


fadeIn(speed, callback)

fadeIn(speed, callback)
fadeIn(speed, callback)

通过不透明度的变化来实现所有匹配元素的淡入效果，并在动画完成后可选地触发一个回调函数。

这个动画只调整元素的不透明度，也就是说所有匹配的元素的高度和宽度不会发生变化。

返回值:jQuery

参数:

  • speed (String|Number): (可选) 三种预定速度之一的字符串("slow", "normal", or "fast")或表示动画时长的毫秒数值(如：1000)
  • callback (Function): (可选) 在动画完成时执行的函数

示例:

$("p").fadeIn("slow");

示例:

$("p").fadeIn("slow",function(){ alert("Animation Done."); });

fadeIn( speed, callback )

Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.

Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.

Return value: jQuery
Parameters:

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").fadeIn("slow");

Example:

 $("p").fadeIn("slow",function(){     alert("Animation Done.");   });


fadeOut(speed, callback)

fadeOut(speed, callback)
fadeOut(speed,callback)

通过不透明度的变化来实现所有匹配元素的淡出效果，并在动画完成后可选地触发一个回调函数。

这个动画只调整元素的不透明度，也就是说所有匹配的元素的高度和宽度不会发生变化。

返回值:jQuery

参数:

  • speed (String|Number): (可选) 三种预定速度之一的字符串("slow", "normal", or "fast")或表示动画时长的毫秒数值(如：1000)
  • callback (Function): (可选) 在动画完成时执行的函数

示例:

$("p").fadeOut("slow");

示例:

$("p").fadeOut("slow",function(){ alert("Animation Done."); });

fadeOut( speed, callback )

Fade out all matched elements by adjusting their opacity and firing an optional callback after completion.

Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.

Return value: jQuery
Parameters:

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").fadeOut("slow");

Example:

 $("p").fadeOut("slow",function(){     alert("Animation Done.");   });


fadeTo(speed, opacity, callback)

fadeTo(speed, opacity, callback)
fadeTo(speed,opacity,callback)

把所有匹配元素的不透明度以渐进方式调整到指定的不透明度，并在动画完成后可选地触发一个回调函数。

这个动画只调整元素的不透明度，也就是说所有匹配的元素的高度和宽度不会发生变化。

返回值:jQuery

参数:

  • speed (String|Number): 三种预定速度之一的字符串("slow", "normal", or "fast")或表示动画时长的毫秒数值(如：1000)
  • opacity (Number): 要调整到的不透明度值(0到1之间的数字).
  • callback (Function): (可选) 在动画完成时执行的函数

示例:

$("p").fadeTo("slow", 0.5);

示例:

$("p").fadeTo("slow", 0.5, function(){ alert("Animation Done."); });

fadeTo(speed,opacity,callback)

Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.

Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.

Return value: jQuery
Parameters:

  • speed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • opacity (Number): The opacity to fade to (a number from 0 to 1).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").fadeTo("slow", 0.5);

Example:

 $("p").fadeTo("slow", 0.5, function(){     alert("Animation Done.");   });


hide(speed,callback)

hide(speed,callback)
hide(speed,callback)

以优雅的动画隐藏所有匹配的元素，并在显示完成后可选地触发一个回调函数。 可以根据指定的速度动态地改变每个匹配元素的高度、宽度和不透明度。

返回值:jQuery

参数:

  • speed (String|Number): 三种预定速度之一的字符串("slow", "normal", or "fast")或表示动画时长的毫秒数值(如：1000)
  • callback (Function): (可选) 在动画完成时执行的函数

示例:

$("p").hide("slow");

示例:

$("p").hide("slow",function(){ alert("Animation Done."); });

hide( speed, callback )

Hide all matched elements using a graceful animation and firing an optional callback after completion.

The height, width, and opacity of each of the matched elements are changed dynamically according to the specified speed.

Return value: jQuery
Parameters:

  • speed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").hide("slow");
Example:
 $("p").hide("slow",function(){     alert("Animation Done.");   });


hide

hide
hide()

隐藏显示的元素。

返回值:jQuery

示例:

$("p").hide()

HTML 代码:

<p>Hello</p>

结果:

[ <p style="display: none">Hello</p> ]

hide()

Hides each of the set of matched elements if they are shown.

Return value: jQuery
Example:

 $("p").hide()
Before:
 <p>Hello</p>
Result:
 [ <p style="display: none">Hello</p> ]


show(speed,callback)

show(speed,callback)
show(speed,callback)

以优雅的动画显示所有匹配的元素，并在显示完成后可选地触发一个回调函数。

可以根据指定的速度动态地改变每个匹配元素的高度、宽度和不透明度。

返回值:jQuery

参数:

  • speed (String|Number): 三种预定速度之一的字符串("slow", "normal", or "fast")或表示动画时长的毫秒数值(如：1000)
  • callback (Function): (可选) 在动画完成时执行的函数

示例:

$("p").show("slow");

示例:

$("p").show("slow",function(){ alert("Animation Done."); });

show(speed,callback)

Show all matched elements using a graceful animation and firing an optional callback after completion.

The height, width, and opacity of each of the matched elements are changed dynamically according to the specified speed.

Return value: jQuery
Parameters:

  • speed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").show("slow");

Example:

 $("p").show("slow",function(){     alert("Animation Done.");   });


show

show
show()

显示隐藏的匹配元素。

返回值:jQuery

示例:

$("p").show()

HTML 代码:

<p style="display: none">Hello</p>

结果:

[ <p style="display: block">Hello</p> ]

show()

Displays each of the set of matched elements if they are hidden.

Return value: jQuery
Example:

 $("p").show()
Before:
 <p style="display: none">Hello</p>
Result:
 [ <p style="display: block">Hello</p> ]


slideDown(speed, callback)

slideDown(speed, callback)
slideDown(speed,callback)

通过高度变化（向下增大）来动态地显示所有匹配的元素，在显示完成后可选地触发一个回调函数。

这个动画效果只调整元素的高度，可以使匹配的元素以“滑动”的方式显示出来。

返回值:jQuery

参数:

  • speed (String|Number): (可选) 三种预定速度之一的字符串("slow", "normal", or "fast")或表示动画时长的毫秒数值(如：1000)
  • callback (Function): (可选) 在动画完成时执行的函数

示例:

$("p").slideDown("slow");

示例:

$("p").slideDown("slow",function(){ alert("Animation Done."); });

slideDown( speed, callback )

Reveal all matched elements by adjusting their height and firing an optional callback after completion.

Only the height is adjusted for this animation, causing all matched elements to be revealed in a "sliding" manner.

Return value: jQuery
Parameters:

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").slideDown("slow");

Example:

 $("p").slideDown("slow",function(){     alert("Animation Done.");   });
slideDown( speed, callback )

Reveal all matched elements by adjusting their height and firing an optional callback after completion.

Only the height is adjusted for this animation, causing all matched elements to be revealed in a "sliding" manner.

Return value: jQuery
Parameters:

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").slideDown("slow");

Example:

 $("p").slideDown("slow",function(){     alert("Animation Done.");   });


slideToggle(speed, callback)

slideToggle(speed, callback)
slideToggle(speed,callback)

通过高度变化来切换所有匹配元素的可见性，并在切换完成后可选地触发一个回调函数。

这个动画效果只调整元素的高度，可以使匹配的元素以“滑动”的方式隐藏或显示。

返回值:jQuery

参数:

  • speed (String|Number): (可选) 三种预定速度之一的字符串("slow", "normal", or "fast")或表示动画时长的毫秒数值(如：1000)
  • callback (Function): (可选) 在动画完成时执行的函数

示例:

$("p").slideToggle("slow");

示例:

$("p").slideToggle("slow",function(){ alert("Animation Done."); });

slideDown( speed, callback )

Reveal all matched elements by adjusting their height and firing an optional callback after completion.

Only the height is adjusted for this animation, causing all matched elements to be revealed in a "sliding" manner.

Return value: jQuery
Parameters:

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").slideDown("slow");

Example:

 $("p").slideDown("slow",function(){     alert("Animation Done.");   });
slideToggle( speed, callback )

Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion.

Only the height is adjusted for this animation, causing all matched elements to be hidden in a "sliding" manner.

Return value: jQuery
Parameters:

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").slideToggle("slow");

Example:

 $("p").slideToggle("slow",function(){     alert("Animation Done.");   });


slideUp(speed, callback)

slideUp(speed, callback)
slideUp(speed, callback)

通过高度变化（向上减小）来动态地隐藏所有匹配的元素，在隐藏完成后可选地触发一个回调函数。

这个动画效果只调整元素的高度，可以使匹配的元素以“滑动”的方式隐藏起来。

返回值:jQuery

参数:

  • speed (String|Number): (可选) 三种预定速度之一的字符串("slow", "normal", or "fast")或表示动画时长的毫秒数值(如：1000)
  • callback (Function): (可选) 在动画完成时执行的函数

示例:

$("p").slideUp("slow");

示例:

$("p").slideUp("slow",function(){ alert("Animation Done."); });

slideDown( speed, callback )

Reveal all matched elements by adjusting their height and firing an optional callback after completion.

Only the height is adjusted for this animation, causing all matched elements to be revealed in a "sliding" manner.

Return value: jQuery
Parameters:

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").slideDown("slow");

Example:

 $("p").slideDown("slow",function(){     alert("Animation Done.");   });
slideUp( speed, callback )

Hide all matched elements by adjusting their height and firing an optional callback after completion.

Only the height is adjusted for this animation, causing all matched elements to be hidden in a "sliding" manner.

Return value: jQuery
Parameters:

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").slideUp("slow");
Example:
 $("p").slideUp("slow",function(){     alert("Animation Done.");   });


toggle()

toggle()
toggle()

切换元素的可见状态。如果元素是可见的，切换为隐藏的；如果元素是隐藏的，切换为可见的。

返回值:jQuery

示例:

$("p").toggle()

HTML 代码:

<p>Hello</p><p style="display: none">Hello Again</p>

结果:

[ <p style="display: none">Hello</p>, <p style="display: block">Hello Again</p> ]

slideDown( speed, callback )

Reveal all matched elements by adjusting their height and firing an optional callback after completion.

Only the height is adjusted for this animation, causing all matched elements to be revealed in a "sliding" manner.

Return value: jQuery
Parameters:

  • speed (String|Number): (optional) A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback (Function): (optional) A function to be executed whenever the animation completes, executes once for each element animated against.

Example:

 $("p").slideDown("slow");

Example:

 $("p").slideDown("slow",function(){     alert("Animation Done.");   });
toggle()

Toggles each of the set of matched elements. If they are shown, toggle makes them hidden. If they are hidden, toggle makes them shown.

Return value: jQuery
Example:

 $("p").toggle()
Before:
 <p>Hello</p><p style="display: none">Hello Again</p>
Result:
 [ <p style="display: none">Hello</p>, <p style="display: block">Hello Again</p> ]


Javascript

Javascript

Boolean $.browser 包含从navigator对象中读取的用户代理标签（代理检测）。

Object $.each(Object obj,Function fn) 一个通用的迭代函数，可用于近似地迭代对象和数组。

Object $.extend(Object target,Object prop1,Object propN ) 用一个或多个其他对象来扩展一个对象，返回这个被扩展的对象。

Array $.grep(Array array,Function fn,Boolean inv) 使用筛选函数，从一个数组中筛选项目。

Array $.map(Array array,Function fn) 把一个数组中的项目转换到另一个数组中

Array $.merge(Array first,Array second) 合并两个数组，删除其中重复的项目。

String $.trim(String str) 删除字符串两端的空白字符。


$.browser

$.browser
$.browser

包含从navigator.userAgent属性中读取的用户代理标签（代理检测）。

有效的标签有：safari, opera, msie, mozilla 这个属性在DOM载入完成之前就可以访问，所以可以使用它来针对某个浏览器添加ready事件。

有的时候，对象检测可能不太可靠，这时就有必要使用浏览器检测。最好是两种方式都不用！ 把浏览器和对象检测结合使用，可以得到相当可靠的结果。

返回值:Boolean

示例:

如果当前的用户代理是IE的某个版本就返回true。

$.browser.msie

示例:

只在safari浏览器中提示－"this is safari!"。

if($.browser.safari) { $( function() { alert("this is safari!"); } ); }

$.browser

Contains flags for the useragent, read from navigator.userAgent. Available flags are: safari, opera, msie, mozilla

This property is available before the DOM is ready, therefore you can use it to add ready events only for certain browsers.

There are situations where object detections is not reliable enough, in that cases it makes sense to use browser detection. Simply try to avoid both!

A combination of browser and object detection yields quite reliable results.

Return value: Boolean
Example:

Returns true if the current useragent is some version of microsoft's internet explorer

$.browser.msie

Example:

Alerts "this is safari!" only for safari browsers

 if($.browser.safari) { $( function() { alert("this is safari!"); } ); }


$.each(obj, fn)

$.each(obj, fn)
$.each(obj, fn)

一个通用的迭代函数，可用于近似地迭代对象和数组。

这个函数与$().each()不同，$().each()是专门用于迭代和执行jQuery对象的函数。而这个函数可以用于迭代任何对象和数组。 这个函数的回调中包含两个参数：第一个是key（对象）或index（数组），第二个是值。

返回值:Object

参数:

  • obj (Object): 要重复迭代的对象或数组
  • fn (Function): 要在每个对象中执行的函数
示例:

这是一个迭代数组中所有项目的例子，通过函数访问了其中的每个项目和索引。

$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); });

示例:

这是一个迭代对象中所有属性的例子，通过函数访问了每个属性的名称和值。

$.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " + i + ", Value: " + n ); });

$.each( obj, fn )

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. This function is not the same as $().each() - which is used to iterate, exclusively, over a jQuery object. This function can be used to iterate over anything.

The callback has two arguments:the key (objects) or index (arrays) as the first, and the value as the second.

If you wish to break the each() loop at a particular iteration you can do so by making your function return false. Other return values are ignored.

Return value: Object
Parameters:

  • obj (Object): The object, or array, to iterate over.
  • fn (Function): The function that will be executed on every object.

Example:

This is an example of iterating over the items in an array, accessing both the current item and its index.

 $.each( [0,1,2], function(i, n){     alert( "Item #" + i + ": " + n );   });

Example:

This is an example of iterating over the properties in an Object, accessing both the current item and its key.

 $.each( { name: "John", lang: "JS" }, function(i, n){     alert( "Name: " + i + ", Value: " + n );   });


$.extend(target, prop1, propN)

$.extend(target, prop1, propN)
$.extend(target,prop1,propN)

用一个或多个其他对象来扩展一个对象，返回这个被扩展的对象。这是简化继承的主要工具。

返回值:Object

参数:

  • target (Object): 要扩展的对象
  • prop1 (Object): 要与第一个对象合并的对象
  • propN (Object): (可选) 更多要与第一个对象合并的对象
示例:

合并settings和options, 修改并返回settings

var settings = { validate: false, limit: 5, name: "foo"   };
var options = { validate: true, name: "bar" };
jQuery.extend(settings,   options);

结果:

settings == { validate: true, limit: 5, name: "bar" }

示例:

合并defaults和options, 但不修改defaults，返回合并后的对象

ar defaults = { validate: false, limit: 5, name: "foo"   };
var options = { validate: true, name: "bar" };
var settings =   jQuery.extend({}, defaults, options);

结果:

settings == { validate: true, limit: 5, name: "bar" }

$.extend( target, prop1, propN )

Extend one object with one or more others, returning the original, modified, object. This is a great utility for simple inheritance.

Return value: Object
Parameters:

  • target (Object): The object to extend
  • prop1 (Object): The object that will be merged into the first.
  • propN (Object): (optional) More objects to merge into the first

Example:

Merge settings and options, modifying settings

var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);
Result:
 settings == { validate: true, limit: 5, name: "bar" }

Example:

Merge defaults and options, without modifying the defaults

 var empty = {};
 var defaults = { validate: false, limit: 5, name: "foo" };
 var options = { validate: true, name: "bar" };
 var settings = jQuery.extend(empty, defaults, options);
Result:
 settings == { validate: true, limit: 5, name: "bar" }
 empty == { validate: true, limit: 5, name: "bar" }


$.grep(array, fn, inv)

$.grep(array, fn, inv)
$.grep(array,fn,inv)

使用筛选函数，从一个数组中筛选项目。 其中筛选函数必须传递两个参数：数组中的当前项目和数组中项目的索引。如果要保持数组中的项目，这个函数必须返回true；如果返回false，就会删除项目。

返回值:Array

参数:

  • array (Array): 要在其中查找项目的数组
  • fn (Function): 处理数组项目的函数
  • inv (Boolean): 反转选项 - 选择相反的筛选结果

示例:

$.grep( [0,1,2], function(i){ return i > 0; });

结果:

[1, 2]

$.grep( array, fn, inv )

Filter items out of an array, by using a filter function.

The specified function will be passed two arguments: The current array item and the index of the item in the array. The function must return 'true' to keep the item in the array, false to remove it.

Return value: Array
Parameters:

  • array (Array): The Array to find items in.
  • fn (Function): The function to process each item against.
  • inv (Boolean): Invert the selection - select the opposite of the function.

Example:

 $.grep( [0,1,2], function(n,i){     return n > 0;   });
Result:
 [1, 2]


$.map(array, fn)

$.map(array, fn)
$.map(array, fn)

把一个数组中的项目转换到另一个数组中。

作为参数的转换函数会被每个数组项目调用，而且会给这个转换函数传递一个表示要转换的项目的参数。 转换函数可以返回转换后的值、null（删除数组中的项目）或一个包含值的数组－－表示对原始数组项目的扩展模式。

返回值:Array

参数:

  • array (Array): 要转换的数组
  • fn (Function): 处理数组项目的函数
示例:

把原始的数组映射到一个新数组中，并给新数组中的每个值都加上4。

$.map( [0,1,2], function(i){ return i + 4; });

结果:

[4, 5, 6]

示例:

把原始的数组映射到一个新数组中，如果新数组中的值大于0，就给这个值加上1；否则将这值删除。

$.map( [0,1,2], function(i){ return i > 0 ? i + 1 : null; });

结果:

[2, 3]

示例:

把原始的数组映射到一个新数组中，将新数组中的每一个元素都扩展为两个，其中一个是其原始值，另一个是加上1之后的值。

$.map( [0,1,2], function(i){ return [ i, i + 1 ]; });

结果:

[0, 1, 1, 2, 2, 3]

$.map( array, fn )

Translate all items in an array to another array of items.

The translation function that is provided to this method is called for each item in the array and is passed one argument: The item to be translated.

The function can then return the translated value, 'null' (to remove the item), or an array of values - which will be flattened into the full array.

Return value: Array
Parameters:

  • array (Array): The Array to translate.
  • fn (Function): The function to process each item against.

Example:

Maps the original array to a new one and adds 4 to each value.

 $.map( [0,1,2], function(n){     return n + 4;   });
Result:
 [4, 5, 6]

Example:

Maps the original array to a new one and adds 1 to each value if it is bigger then zero, otherwise it's removed-

 $.map( [0,1,2], function(n){     return n > 0?? n + 1?: null;   });
Result:
 [2, 3]

Example:

Maps the original array to a new one, each element is added with it's original value and the value plus one.

 $.map( [0,1,2], function(n){     return [ n, n + 1 ];   });
Result:
 [0, 1, 1, 2, 2, 3]


$.merge(first, second)

$.merge(first, second)
$.merge(first,second)

合并两个数组，删除其中重复的项目。

得到的新数组是：第一个数组中的所有项目，加上第二个数组中唯一的（不与第一个数组中任何项目相同的）项目。

返回值:Array

参数:

  • first (Array): 要合并的第一个数组
  • second (Array): 要合并的第二个数组
示例:

合并两个数组，删除其中重复的2

$.merge( [0,1,2], [2,3,4] )

结果:

[0,1,2,3,4]

示例:

合并两个数组，删除重复的3和2。

$.merge( [3,2,1], [4,3,2] )

结果:

[3,2,1,4]

$.merge( first, second )

Merge two arrays together, removing all duplicates.

The result is the altered first argument with the unique elements from the second array added.

Return value: Array
Parameters:

  • first (Array): The first array to merge, the unique elements of second added.
  • second (Array): The second array to merge into the first, unaltered.

Example:

Merges two arrays, removing the duplicate 2

 $.merge( [0,1,2], [2,3,4] )
Result:
 [0,1,2,3,4]

Example:

Merges two arrays, removing the duplicates 3 and 2

 var array = [3,2,1];   $.merge( array, [4,3,2] )
Result:
 array == [3,2,1,4]


$.trim(str)

$.trim(str)
$.trim(str)

删除字符串两端的空白字符。

返回值:String

参数:

  • str (String): 要删除空白字符的字符串

示例:

$.trim(" hello, how are you? ");

结果:

"hello, how are you?"

$.trim( str )

Remove the whitespace from the beginning and end of a string.

Return value: String
Parameters:

  • str (String): The string to trim.

Example:

 $.trim("  hello, how are you?  ");
Result:
 "hello, how are you?"


Ajax

Ajax

XMLHttpRequest $.ajax(Map properties) 使用HTTP请求（XMLHttpRequest）载入一个远程页面。

undefined $.ajaxSetup（Map properties） Ajax请求全局设置

undefined $.ajaxTimeout(Number time) Ajax请求超时设置

XMLHttpRequest　$.get(String url,Hash params,Function callback) 用GET方法请求装入一个远程页面

XMLHttpRequest $.getIfModified(String url,Hash params,Function callback) 用GET方法请求请求一个修改后的页面

XMLHttpRequest $.getJSON(String url,Hash params,Function callback) 用GET方法请求一装入一个远程JSON对象

XMLHttpRequest $.getScript(String url,Function callback ) 用GET方法装入并执行一个远程JavaScript文件

XMLHttpRequest $.post(String url,Hash params,Function callback) 用POST方法请求一个远程页面

jQuery　ajaxComplete(Function callback) 绑定Ajax请求完成时执行回调函数数

jQuery ajaxError(Function callback) 绑定Ajax请求失败时执行回调函数

jQuery ajaxSend(Function callback) 绑定请一个Ajax请求发送时要执行的函数

jQuery ajaxStart(Function callback) 绑定一个Ajax请求开始时执行的回调函数

jQuery ajaxStop(Function callback) 绑定一个Ajax请求停止时执行的回调函数

jQuery ajaxSuccess(Function callback)　绑定一个Ajax请求顺利完成时执行的回调函数

jQuery load(String url,Object params,Function callback) 装入一个远程文件页面请求内容到DOM元素

jQuery loadIfModified(String url,Map params,Function callback ) 当远程文件修改后，装入修改后的远程文件页请内容到DOM元素

String serialize() 把Input元素的内容连接成为一个请求字符串


$.ajax(properties)

$.ajax(properties)

$.ajax(properties)

使用HTTP请求（XMLHttpRequest）载入一个远程页面。

这是jQuery的低级AJAX实现。要查看高级抽象，见$.set、$.post等。

$.ajax()返回创建好的XMLHttpRequest对象。多数情况下并不需要直接操纵这个对象，但是如果需要手动中止请求，它也是可用的。

注意：要确保服务器返回正确的MIME类型（例如：XML是“text/xml”）。如果返回了错误的MIME类型就会导致jQuery无法处理的严重问题。

支持的数据类型包括（见dataType选项）：

"xml": 返回一个可以由jQuery对象处理的XML文档。

"html": 返回纯文本格式的HTML，包括求值后的脚本标记。

"script": 将响应作为Javascript语句求值，并返回纯文本。

"json": 将响应作为JSON求值，并返回一个Javascript对象。

$.ajax()带有一个参数－－“名/值对”形式的一个对象，用于初始化和处理请求。以下就是可用的所有“名/值对”：

(String) url - 要将请求发送到的URL地址。

(String) type - 请求的类型 ("POST" 或 "GET"), 默认是 "GET"。

(String) dataType - 期望从服务器端返回的数据类型。无默认值：如果服务器返回XML，就将responseXML传递到回调函数，否则将resposeText传递到回调函数。

(Boolean) ifModified - 只有响应自上次请求后被修改过才承认是成功的请求。是通过检查头部的Last-Modified值实现的。默认值为false，即忽略 对部分的检查

(Number) timeout - 覆盖全局延迟的局部延迟，例如，在其他所有延迟经过1秒钟后，启动一个较长延迟的单独请求。有关全局延迟，见$.ajaxTimeout()。

(Boolean) global - 是否为当前的请求触发全局AJAX事件处理函数，默认值为true。设置为false可以防止触发像ajaxStart或ajaxStop这样的全局事件处理函数。

(Function) error - 当请求失败时调用的函数。这个函数会得到三个参数：XMLHttpRequest对象、一个描述所发生的错误类型的字符串和一个可选异常对象（如果有）。

(Function) success - 当请求成功时调用的函数。这个函数会得到一个参数：从服务器返回的数据（根据“dataType”进行了格式化）。

(Function) complete - 当请求完成时调用的函数。这个函数会得到两个参数：XMLHttpRequest对象和一个描述请求成功的类型的字符串。

(Object|String) data - 要发送到服务器的数据。如果还不是一个字符串，就自动轮换为一个查询字符串。即附加到GET请求的url后面的字符串。要防止自动处理见processData选项。

(String) contentType - 设置发送请求的content=type。默认值是 "application/x-www-form-urlencoded", 这个值能满足多数情况。

(Boolean) processData - 在默认的情况下，如果data选项传进的数据是一个对象而不是字符串，将会自动地被处理和转换成一个查询字符串，以适应默认的content-type－－"application/x-www-form-urlencoded"。如果想发送DOMDocuments，就要把这个选项设置为false。

(Boolean) async - 在默认的情况下，所有请求都是以异步的方式发送的（值为true）。如果要使用同步方式，需要将此项设置为false。

(Function) beforeSend - 用于设置自定义头部等信息的预调用函数，接收一个唯一的参数－－XMLHttpRequest对象。

返回值：XMLHttpRequest

参数：

  • properties (Map): Key/value pairs to initialize the request with.
示例：

载入并执行一个JavaScript文件。

$.ajax({
 type: "GET",
 url: "test.js",
 dataType:   "script"
})
示例：

将数据保存到服务器，并在保存完成后通报用户。

$.ajax({
 type: "POST",
 url: "some.php",
 data:   "name=John&location=Boston",
 success: function(msg){ alert( "Data Saved: " +   msg ); }
});
示例：

同步载入数据。当请求处于活动期间阻塞浏览器。如果必须同步载入数据，最好是通过其他手段来阻止用户的交互，而不是阻塞整个浏览器。

ar html = $.ajax({
 url: "some.php",
 async: false
}).responseText;
示例：

将一个XML文档作为数据发送到服务器。通过将processData选项设置为false，可以避免把自动把数据转换为字符串。

ar xmlDocument = [create xml document];
$.ajax({
 url:   "page.php",
 processData: false,
 data: xmlDocument,
 success: handleResponse
});
$.ajax( properties )

Load a remote page using an HTTP request.

This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks).

$.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually.

Note: If you specify the dataType option described below, make sure the server sends the correct MIME type in the response (eg. xml as "text/xml"). Sending the wrong MIME type can lead to unexpected problems in your script. See Specifying the Data Type for AJAX Requests for more information.

Options

$.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request. These are all the key/values that can be used:

  • async (Boolean) - By default, all requests are sent asynchronous (e.g. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
  • beforeSend (Function) - A pre-callback to modify the XMLHttpRequest object before it is sent. Use this to set custom headers etc. The XMLHttpRequest is passed as the only argument.
  • complete (Function) - A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.
  • contentType (String) - When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases.
  • data (Object|String) - Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing.
  • dataType (String) - The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response. The available types (and the result passed as the first argument to your success callback) are:
    • "xml": Returns a XML document that can be processed via jQuery.
    • "html": Returns HTML as plain text; included script tags are evaluated.
    • "script": Evaluates the response as JavaScript and returns it as plain text.
    • "json": Evaluates the response as JSON and returns a JavaScript Object.
  • error (Function) - A function to be called if the request fails. The function gets passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred.
  • global (Boolean) - Whether to trigger global AJAX event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered.
  • ifModified (Boolean) - Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header.
  • processData (Boolean) - By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments, or other non-processed data, set this option to false.
  • success (Function) - A function to be called if the request succeeds. The function gets passed one argument: The data returned from the server, formatted according to the 'dataType' parameter.
  • timeout (Number) - Set a local timeout in ms for the request. This will override the global timeout, if one is set via $.ajaxTimeout. For example, you could use this property to give a single request a longer timeout than all other requests that you've set to time out in one second. See $.ajaxTimeout() for global timeouts.
  • type (String) - The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
  • url (String) - The URL to request.

Return value: XMLHttpRequest
Parameters:

  • properties (Map): Key/value pairs to initialize the request with.

Example:

Load and execute a JavaScript file.

 $.ajax({
     type: "GET",
     url: "test.js",
    dataType: "script"
})

Example:

Save some data to the server and notify the user once its complete.

 $.ajax({
     type: "POST",
     url: "some.php",
     data: "name=John&location=Boston",
     success: function(msg){       alert( "Data Saved: " + msg );     }
});

Example:

Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction by other means when synchronization is necessary.

 var html = $.ajax({
    url: "some.php",
    async: false
}).responseText;

Example:

Sends an xml document as data to the server. By setting the processData option to false, the automatic conversion of data to strings is prevented.

 var xmlDocument = [create xml document];
 $.ajax({
     url: "page.php",
     processData: false,
     data: xmlDocument,
     success: handleResponse
});


$.ajaxSetup(settings)

$.ajaxSetup(settings)
$.ajaxSetup(settings)

Ajax请求全局设置，详细请$.ajax选项描述。

返回值：undefined

参数：

  • settings (Map): 用于Ajax请求的键／值对。

示例：

设置默认请求url为"/xmlhttp/",无全局操作权限，用ＰＯＳＴ方法请求。下面用Ajax请求一些数据！
$.ajaxSetup( {
 url: "/xmlhttp/",
 global: false,
 type:   "POST"
} );
$.ajax({ data: myData });
$.ajaxSetup( settings )

Setup global settings for AJAX requests.

See $.ajax for a description of all available options.

Return value: undefined
Parameters:

  • settings (Map): Key/value pairs to use for all AJAX requests

Example:

Sets the defaults for AJAX requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET. The following AJAX requests then sends some data without having to set anything else.

 $.ajaxSetup( {
    url: "/xmlhttp/",
     global: false,
     type: "POST"
} );
$.ajax({ data: myData });


$.ajaxTimeout(time)

$.ajaxTimeout(time)
$.ajaxTimeout(time)

Ajax请求超时设定，该设定限制将要进行Ajax请求响应最大需要的时间，如果设置为null或者0即不超时（默认）。

返回值：undefined

参数：

  • time (Number): AJAX请求在多少时间之前完成。
示例：

设置Ajax请求超时为5秒钟。

$.ajaxTimeout( 5000 );

$.ajaxTimeout( time )

Set the timeout of all AJAX requests to a specific amount of time. This will make all future AJAX requests timeout after a specified amount of time.

Set to null or 0 to disable timeouts (default).

You can manually abort requests with the XMLHttpRequest's (returned by all ajax functions) abort() method.

Deprecated. Use $.ajaxSetup instead.

Return value: undefined
Parameters:

  • time (Number): How long before an AJAX request times out.

Example:

Make all AJAX requests timeout after 5 seconds.

 $.ajaxTimeout( 5000 );


$.get(url, params, callback)

$.get(url, params, callback)
$.get(url, params, callback)

用GET方式请求装入远程页面

返回值：XMLHttpRequest

参数：

  • url (String): 装入页面的URL地址。
  • params (Map): （可选）发送到服务端的键／值对参数。
  • callback (Function): （可选） 当远程页面装入完成时执行的函数.

示例：

$.get("test.cgi");

示例：

$.get("test.cgi", { name: "John", time: "2pm" } );

示例：

$.get("test.cgi", function(data){ alert("Data Loaded: " + data); });

示例：

$.get("test.cgi", { name: "John", time: "2pm" },
   function(data){
    alert("Data Loaded: " + data);
   }
);
$.get( url, params, callback )

Load a remote page using an HTTP GET request.

This is an easy way to send a simple GET request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). If you need to have both error and success callbacks, you may want to use $.ajax.

Return value: XMLHttpRequest
Parameters:

  • url (String): The URL of the page to load.
  • params (Map): (optional) Key/value pairs that will be sent to the server.
  • callback (Function): (optional) A function to be executed whenever the data is loaded successfully.

Example:

 $.get("test.cgi");

Example:

 $.get("test.cgi", { name: "John", time: "2pm" } );

Example:

 $.get("test.cgi",
 function(data){
     alert("Data Loaded: " + data);
   }
);

Example:

 $.get(
     "test.cgi",
     { name: "John", time: "2pm" },
     function(data){
       alert("Data Loaded: " + data);
     }
);


$.getIfModified(url, params, callback)

$.getIfModified(url, params, callback)
$.getIfModified(url, params, callback)

当远程页面被修改后，用该函数通过HTTP GET请求方式装入远程页面。

返回值：XMLHttpRequest

参数：

  • url (String): 装入页面的URL地址
  • params (Map): （可选）发送到服务端的键／值对参数。
  • callback (Function):（可选） 当远程页面装入完成时执行的函数.

示例：

$.getIfModified("test.html");

示例：

$.getIfModified("test.html", { name: "John", time: "2pm" } );

示例：

$.getIfModified("test.cgi", function(data){ alert("Data Loaded: " + data); });

示例：

$.getifModified(
  "test.cgi",
 { name: "John", time: "2pm"   },
 function(data){
   alert("Data Loaded: " + data);
 }
 );
$.getIfModified(url, params, callback)

Load a remote page using an HTTP GET request, only if it hasn't been modified since it was last retrieved.

Return value: XMLHttpRequest
Parameters:

  • url (String): The URL of the page to load.
  • params (Map): (optional) Key/value pairs that will be sent to the server.
  • callback (Function): (optional) A function to be executed whenever the data is loaded successfully.

Example:

 $.getIfModified("test.html");

Example:

 $.getIfModified("test.html", { name: "John", time: "2pm" } );

Example:

 $.getIfModified("test.cgi", function(data){     alert("Data Loaded: " + data);   });

Example:

 $.getIfModified("test.cgi",
    { name: "John", time: "2pm" },
     function(data){
      alert("Data Loaded: " + data);
    }
);


$.getJSON(url, params, callback)

$.getJSON(url, params, callback)
$.getJSON(url, params, callback)

用一个HTTP GET请求一个JavaScript JSON数据

返回值：XMLHttpRequest

参数：

  • url (String): 装入页面的URL地址。
  • params (Map): （可选）发送到服务端的键／值对参数。
  • callback (Function): （可选） 当数据装入完成时执行的函数.

示例：

$.getJSON(
  "test.js",
  function(json){
    alert("JSON Data:   " + json.users[3].name);
  }
);

示例：

$.getJSON(
   "test.js",
  { name: "John", time: "2pm" },
   function(json){
     alert("JSON Data: " + json.users[3].name);
  }
);
$.getJSON( url, params, callback )

Load JSON data using an HTTP GET request.

Return value: XMLHttpRequest
Parameters:

  • url (String): The URL of the page to load.
  • params (Map): (optional) Key/value pairs that will be sent to the server.
  • callback (Function): A function to be executed whenever the data is loaded successfully.

Example:

 $.getJSON(
   "test.js",
   function(json){
     alert("JSON Data: " + json.users[3].name);
   }
 );

Example:

 $.getJSON(
     "test.js",
     { name: "John", time: "2pm" },
     function(json){
       alert("JSON Data: " + json.users[3].name);
     }
 );


$.getScript(url, callback)

$.getScript(url, callback)
$.getScript(url, callback)

用GET方式装入并执行一个远程JavaScript文件。

注意：Safari在2.0.x或以下版本脚本不能全局内容同步，如果你通过getScript装入一个函数，请确信延迟正确装入后调用。

返回值：XMLHttpRequest

参数：

  • url (String): 装入页面的URL地址
  • callback (Function): （可选） 当数据装入完成时执行的函数.

示例：

$.getScript("test.js");

示例：

$.getScript("test.js",
   function(){
     alert("Script loaded   and executed.");
   }
);
$.getScript( url, callback )

Loads, and executes, a remote JavaScript file using an HTTP GET request.

Warning: Safari <= 2.0.x is unable to evaluate scripts in a global context synchronously. If you load functions via getScript, make sure to call them after a delay.

Return value: XMLHttpRequest
Parameters:

  • url (String): The URL of the page to load.
  • callback (Function): (optional) A function to be executed whenever the data is loaded successfully.

Example:

 $.getScript("test.js");

Example:

 $.getScript("test.js",
   function(){
     alert("Script loaded and executed.");
   }
 );


$.post(url, params, callback)

$.post(url, params, callback)
$.post(url, params, callback)

用HTTP POST方式装入一个远程页面

返回值：XMLHttpRequest

参数：

  • url (String): 装入页面的URL地址。
  • params (Map): （可选）发送到服务端的键／值对参数。
  • callback (Function): （可选） 当数据装入完成时执行的函数.

示例：

$.post("test.cgi");

示例：

$.post("test.cgi", { name: "John", time: "2pm" } );

示例：

$.post("test.cgi",
  function(data){
    alert("Data Loaded:   " + data);
   }
);

示例：

$.post("test.cgi",
       { name: "John", time: "2pm" },
       function(data){
          alert("Data Loaded: " + data);
       }
);

$.post( url, params, callback )

Load a remote page using an HTTP POST request.

This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). If you need to have both error and success callbacks, you may want to use $.ajax.

Return value: XMLHttpRequest
Parameters:

  • url (String): The URL of the page to load.
  • params (Map): (optional) Key/value pairs that will be sent to the server.
  • callback (Function): (optional) A function to be executed whenever the data is loaded successfully.

Example:

 $.post("test.cgi");

Example:

 $.post("test.cgi", { name: "John", time: "2pm" } );
Example:
 $.post("test.cgi",
        function(data){
          alert("Data Loaded: " + data);
        }
 );

Example:

 $.post("test.cgi",
     { name: "John", time: "2pm" },
     function(data){
       alert("Data Loaded: " + data);
     }
 );


ajaxComplete(callback)

ajaxComplete(callback)
ajaxComplete(callback)

当AJAX请求完成时执行一个函数。

返回值：jQuery

参数：

  • callback (Function): 要执行的函数。

示例：

当Ajax请求完成时显示一条信息。

$("#msg").ajaxComplete(
  function(request, settings){
    $(this).append("<li>Request Complete.</li>");
  }
);
ajaxComplete( callback )

Attach a function to be executed whenever an AJAX request completes.

The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

Return value: jQuery
Parameters:

  • callback (Function): The function to execute.

Example:

Show a message when an AJAX request completes.

 $("#msg").ajaxComplete(function(request, settings){
     $(this).append("<li>Request Complete.</li>");
 });


ajaxError(callback)

ajaxError(callback)
ajaxError(callback)

绑定一个当一个AJAX请求失败时执行的函数。

返回值：jQuery

参数：

  • callback (Function): 执行的函数。

示例：

显示一个请求失败的信息。

("#msg").ajaxError(function(request, settings){
   $(this).append("<li>Error requesting page " + settings.url +   "</li>");
 });

ajaxError( callback )

Attach a function to be executed whenever an AJAX request fails.

The XMLHttpRequest and settings used for that request are passed as arguments to the callback. A third argument, an exception object, is passed if an exception occured while processing the request.

Return value: jQuery
Parameters:

  • callback (Function): The function to execute.

Example:

Show a message when an AJAX request fails.

 $("#msg").ajaxError(function(request, settings){
     $(this).append("<li>Error requesting page " + settings.url + "</li>");
 });


ajaxSend(callback)

ajaxSend(callback)
ajaxSend(callback)

绑定一个Ajax请求发送时执行的函数。

返回值：jQuery

参数：

  • callback (Function): 用于执行的函数。

示例：

AJAX请求发送时显示一条信息

("#msg").ajaxSend(function(request, settings){
   $(this).append("<li>Starting request at " + settings.url + "</li>");
 });
ajaxSend( callback )

Attach a function to be executed before an AJAX request is sent.

The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

Return value: jQuery
Parameters:

  • callback (Function): The function to execute.

Example:

Show a message before an AJAX request is sent.

 $("#msg").ajaxSend(function(request, settings){
     $(this).append("<li>Starting request at " + settings.url + "</li>");
 });


ajaxStart(callback)

ajaxStart(callback)
ajaxStart(callback)

绑定一个当AJAX请求开始并且还没有开始运行时执行的函数

返回值：jQuery

参数：

  • callback (Function): The function to execute.

示例：

当Ajax请求开始（并没有开始活动）显示一个loading信息。

("#loading").ajaxStart(function(){
     $(this).show();
});
ajaxStart( callback )

Attach a function to be executed whenever an AJAX request begins and there is none already active.

Return value: jQuery
Parameters:

  • callback (Function): The function to execute.

Example:

Show a loading message whenever an AJAX request starts (and none is already active).

 $("#loading").ajaxStart(function(){
     $(this).show();
  });


ajaxStop(callback)

ajaxStop(callback)
ajaxStop(callback)

绑定一个Ajax请求全部结束时执行的函数。

返回值：jQuery

参数：

  • callback (Function): 执行的函数。

示例：

当AJAX请求停止时隐藏Loading信息。

$("#loading").ajaxStop(
  function(){
    $(this).hide();
  }
);
ajaxStop( callback )

Attach a function to be executed whenever all AJAX requests have ended.

Return value: jQuery
Parameters:

  • callback (Function): The function to execute.

Example:

Hide a loading message after all the AJAX requests have stopped.

 $("#loading").ajaxStop(
    function(){
       $(this).hide();
    }
  );


ajaxSuccess(callback)

ajaxSuccess(callback)
ajaxSuccess(callback)

绑定一个当AJAX请求顺利完成时执行的函数。

返回值：jQuery

参数：

  • callback (Function): The function to execute.

示例：

当AJAX顺利完成时显示一条消息。

$("#msg").ajaxSuccess(
  function(request, settings){
   $(this).append("<li>Successful Request!</li>");
  }
);
ajaxSuccess( callback )

Attach a function to be executed whenever an AJAX request completes successfully.

The XMLHttpRequest and settings used for that request are passed as arguments to the callback.

Return value: jQuery
Parameters:

  • callback (Function): The function to execute.

Example:

Show a message when an AJAX request completes successfully.

 $("#msg").ajaxSuccess(function(request, settings){
     $(this).append("<li>Successful Request!</li>");
 });


load(url, params, callback)

load(url, params, callback)
load(url, params, callback)

装入一个远程HTML内容到一个DOM结点。

注意：避免用装入的scripts脚本，装入脚本改用$.getScript.当任何字符显示时，IE会忽略所有的脚本。

返回值：jQuery

参数：

  • url (String): 装入的HTML文件url地址
  • params (Object): （可选）发送到服务端的键／值对参数。
  • callback (Function): （可选） 当数据装入完成时执行的函数.

示例：

$("#feeds").load("feeds.html");

HTML 代码:

<div id="feeds"></div>

结果:

<div id="feeds"><b>45</b> feeds found.</div>

示例：

和上面相似，但加入了当数据装入后执行一个回调函数参数。

$("#feeds").load("feeds.html",
  {limit: 25},
  function()   {
   alert("The last 25 entries in the feed have been loaded");
  }
);
load( url, params, callback )

Load HTML from a remote file and inject it into the DOM.

Note: Avoid using this to load scripts, instead use $.getScript. IE strips script tags when there aren't any other characters in front of it.

Return value: jQuery
Parameters:

  • url (String): The URL of the HTML file to load.
  • params (Object): (optional) A set of key/value pairs that will be sent as data to the server.
  • callback (Function): (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).

Example:

 $("#feeds").load("feeds.html");
Before:
 <div id="feeds"></div>
Result:
 <div id="feeds"><b>45</b> feeds found.</div>

Example:

Same as above, but with an additional parameter and a callback that is executed when the data was loaded.

 $("#feeds").load("feeds.html",
     {limit: 25},
     function() {
       alert("The last 25 entries in the feed have been loaded");
     }
 );


loadIfModified(url, params, callback)

loadIfModified(url, params, callback)
loadIfModified(url, params, callback)

当远程文件修改后，装入修改后的远程文件页请内容到DOM元素.

返回值:jQuery

参数:

  • url (String): 装入的HTML文件url地址
  • params (Map): 可选）发送到服务端的键／值对参数。
  • callback (Function): 可选） 当数据装入完成时执行的函数.

示例:

$("#feeds").loadIfModified("feeds.html");

HTML 代码:

<div id="feeds"></div>

结果:

<div id="feeds"><b>45</b> feeds found.</div>

loadIfModified( url, params, callback )

Load HTML from a remote file and inject it into the DOM, only if it's been modified by the server.

Return value: jQuery
Parameters:

  • url (String): The URL of the HTML file to load.
  • params (Map): (optional) Key/value pairs that will be sent to the server.
  • callback (Function): (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).

Example:

 $("#feeds").loadIfModified("feeds.html");
Before:
 <div id="feeds"></div>
Result:
 <div id="feeds"><b>45</b> feeds found.</div>


serialize()

serialize()
serialize()

把Input元素的内容连接成为一个请求字符串

返回值:String

示例:

Serialize a selection of input elements to a string

HTML 代码:

<input type='text' name='name' value='John'/>
<input type='text' name='location' value='Boston'/>

jQuery 代码:

$("input[@type=text]").serialize();

serialize()

Serializes a set of input elements into a string of data. This will serialize all given elements.

A serialization designed to emulate the actual form submission of a browser is provided by the Form Plugin. The plugin's formSerialize method correctly handles multiple-selects and identically-named checkboxes as arrays, whereas the serialize method recognizes only a single value for these elements.

Return value: String
Example:

Serialize a selection of input elements to a string

 $("input[@type=text]").serialize();
Before:
 <input type='text' name='name' value='John'/>
 <input type='text' name='location' value='Boston'/>
Result:
 name=John&location=Boston


Accordion(settings)

Accordion(settings)

Make the selected elements Accordion widgets. ? Semantic requirements: If the structure of your container is flat with unique tags for header and content elements, eg. a definition list (dl > dt + dd), you don't have to specify any options at all. If your structure uses the same elements for header and content or uses some kind of nested structure, you have to specify the header elements, eg. via class, see the second example. Use activate(Number) to change the active content programmatically.

返回值

jQuery

参数

  • settings (Object): key/value pairs of optional settings.

Hash 选项

  • active (String|Element|jQuery|Boolean): Selector for the active element, default is the first child, set to false to display none at start
  • header (String|Element|jQuery): Selector for the header element, eg. div.title, a.head, default is the first child's tagname
  • showSpeed (String|Number): Speed for the slideIn, default is 'slow'
  • hideSpeed (String|Number): Speed for the slideOut, default is 'fast'
  • selectedClass (String): Class for active header elements, default is 'selected'

示例

说明:

Creates a Accordion from the given definition list

HTML 代码:
<dl id="list1"><dt>Header 1><dd>Content 1</dd>[...]</dl>
jQuery 代码:
$('#list1').Accordion();
说明:

Creates a Accordion from the given div structure

HTML 代码:
<div id="nav"><div><div class="title">Header 1><div>Content 1</div></div>[...]</div>
jQuery 代码:
$('#list2').Accordion({ header: 'div.title' });
说明:

Creates a Accordion from the given navigation list

HTML 代码:
<ul id="nav"> <li> <a class="head">Header 1> <ul> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2></a></li> </ul> </li> [...] </ul>
jQuery 代码:
$('#nav').Accordion({ header: 'a.head' });
说明:

Updates the #status element with the text of the selected header every time the accordion changes

jQuery 代码:
$('#accordion').Accordion().change(function(event, newHeader, oldHeader, newContent, oldContent) { $('#status').html(newHeader.text()); });


activate(index)

activate(index)

Activate a content part of the Accordion programmatically with the position zero-based index. If the index is not specified, it defaults to zero, if it is an invalid index, eg. a string, nothing happens. Requires jQuery core revision >= 557.

返回值

jQuery

参数

  • index (Number): An Integer specifying the zero-based index of the content to be activated. Defaults to 0.

示例

说明:

Activate the second content of the Accordion contained in <div id="accordion">.

jQuery 代码:
$('#accordion').activate(1);
说明:

Activate the first content of the Accordion contained in <ul id="nav">.

jQuery 代码:
$('#nav').activate();


button(hash)

button(hash)

Creates a button from an image element. This function attempts to mimic the functionality of the "button" found in modern day GUIs. There are two different buttons you can create using this plugin; Normal buttons, and Toggle buttons.

返回值

jQuery

参数

  • hash (hOptions): with options, described below. sPath Full path to the images, either relative or with full URL sExt Extension of the used images (jpg|gif|png) sName Name of the button, if not specified, try to fetch from id iWidth Width of the button, if not specified, try to fetch from element.width iHeight Height of the button, if not specified, try to fetch from element.height onAction Function to call when clicked / toggled. In case of a string, the element is wrapped inside an href tag. bToggle Do we need to create a togglebutton? (boolean) bState Initial state of the button? (boolean) sType Type of hover to create (img|css)


center()

center()

Takes all matched elements and centers them, absolutely, within the context of their parent element. Great for doing slideshows.

返回值

jQuery

示例

jQuery 代码:
$("div img").center();


$.cookie(name)

$.cookie(name)

Get the value of a cookie with the given name.

返回值

String

参数

  • name (String): The name of the cookie.

示例

说明:

Get the value of a cookie.

jQuery 代码:
$.cookie('the_cookie');


$.cookie(name, value, options)

$.cookie(name, value, options)

Create a cookie with the given name and value and other optional parameters.

返回值

undefined

参数

  • name (String): The name of the cookie.
  • value (String): The value of the cookie.
  • options (Object): An object literal containing key/value pairs to provide optional cookie attributes.

Hash 选项

  • expires (Number|Date): Either an integer specifying the expiration date from now on in days or a Date object. If a negative value is specified (e.g. a date in the past), the cookie will be deleted. If set to null or omitted, the cookie will be a session cookie and will not be retained when the the browser exits.
  • path (String): The value of the path atribute of the cookie (default: path of page that created the cookie).
  • domain (String): The value of the domain attribute of the cookie (default: domain of page that created the cookie).
  • secure (Boolean): If true, the secure attribute of the cookie will be set and the cookie transmission will require a secure protocol (like HTTPS).

示例

说明:

Set the value of a cookie.

jQuery 代码:
$.cookie('the_cookie', 'the_value');
说明:

Create a cookie with all available options.

jQuery 代码:
$.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
说明:

Create a session cookie.

jQuery 代码:
$.cookie('the_cookie', 'the_value');
说明:

Delete a cookie by setting a date in the past.

jQuery 代码:
$.cookie('the_cookie', '', {expires: -1});


height()

height()

Returns the css height value for the first matched element. If used on document, returns the document's height (innerHeight) If used on window, returns the viewport's (window) height

返回值

Object

示例

jQuery 代码:
$("#testdiv").height()
结果:
"200px"
jQuery 代码:
$(document).height();
结果:
800

jQuery 代码:

$(window).height();
结果:
400


innerHeight()

innerHeight()

Returns the inner height value (without border) for the first matched element. If used on document, returns the document's height (innerHeight) If used on window, returns the viewport's (window) height

返回值

Number

示例

jQuery 代码:
$("#testdiv").innerHeight()
结果:
800


innerWidth()

innerWidth()

Returns the inner width value (without border) for the first matched element. If used on document, returns the document's Width (innerWidth) If used on window, returns the viewport's (window) width

返回值

Number

示例

jQuery 代码:
$("#testdiv").innerWidth()
结果:
1000


offset()

offset()

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, scrollTop, pageXOffset, pageYOffset. The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not the same as the element's scrollTop and scrollLeft. For accurate readings make sure to use pixel values.

返回值

Object

offset(refElement)

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, scrollTop, pageXOffset, pageYOffset. The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not the same as the element's scrollTop and scrollLeft. For accurate readings make sure to use pixel values.

返回值

Object

参数

  • refElement (String): This is an expression. The offset returned will be relative to the first matched element.

offset(refElement)

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, scrollTop, pageXOffset, pageYOffset. The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not the same as the element's scrollTop and scrollLeft. For accurate readings make sure to use pixel values.

返回值

Object

参数

  • refElement (jQuery): The offset returned will be relative to the first matched element.

offset(refElement)

This returns an object with top, left, width, height, borderLeft, borderTop, marginLeft, marginTop, scrollLeft, scrollTop, pageXOffset, pageYOffset. The top and left values include the scroll offsets but the scrollLeft and scrollTop properties of the returned object are the combined scroll offets of the parent elements (not including the window scroll offsets). This is not the same as the element's scrollTop and scrollLeft. For accurate readings make sure to use pixel values.

返回值

Object

参数

  • refElement (HTMLElement): The offset returned will be relative to this element.


outerHeight()

outerHeight()

Returns the outer height value (including border) for the first matched element. Cannot be used on document or window.

返回值

Number

示例

jQuery 代码:
$("#testdiv").outerHeight()
结果:
1000


outerWidth()

outerWidth()

Returns the outer width value (including border) for the first matched element. Cannot be used on document or window.

返回值

Number

示例

jQuery 代码:
$("#testdiv").outerWidth()
结果:
1000


scrollLeft()

scrollLeft()

Returns how many pixels the user has scrolled to the right (scrollLeft). Works on containers with overflow: auto and window/document.

返回值

Number

示例

jQuery 代码:
$("#testdiv").scrollLeft()
结果:
100


scrollTop()

scrollTop()

Returns how many pixels the user has scrolled to the bottom (scrollTop). Works on containers with overflow: auto and window/document.

返回值

Number

示例

jQuery 代码:
$("#testdiv").scrollTop()
结果:
100


width()

width()

Returns the css width value for the first matched element. If used on document, returns the document's width (innerWidth) If used on window, returns the viewport's (window) width

返回值

Object

示例

jQuery 代码:
$("#testdiv").width()
结果:
"200px"
jQuery 代码:
$(document).width();
结果:
800

jQuery 代码:

$(window).width();
结果:
400


ajaxForm(object)

ajaxForm(object)

ajaxForm() provides a mechanism for fully automating form submission. The advantages of using this method instead of ajaxSubmit() are: 1: This method will include coordinates for <input type="image" /> elements (if the element is used to submit the form). 2. This method will include the submit element's name/value data (for the element that was used to submit the form). 3. This method binds the submit() method to the form for you. Note that for accurate x/y coordinates of image submit elements in all browsers you need to also use the "dimensions" plugin (this method will auto-detect its presence). The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely passes the options argument along after properly binding events for submit elements and the form itself. See ajaxSubmit for a full description of the options argument.

返回值

jQuery

参数

  • object (options): literal containing options which control the form submission process

示例

说明:

Bind form's submit event so that 'myTargetDiv' is updated with the server response when the form is submitted.

jQuery 代码:
var options = { target: '#myTargetDiv' }; $('#myForm').ajaxSForm(options);

说明:

Bind form's submit event so that server response is alerted after the form is submitted.

jQuery 代码:
var options = { success: function(responseText) { alert(responseText); } }; $('#myForm').ajaxSubmit(options);

说明:

Bind form's submit event so that pre-submit callback is invoked before the form is submitted.

jQuery 代码:
var options = { beforeSubmit: function(formArray, jqForm) { if (formArray.length == 0) { alert('Please enter data.'); return false; } } }; $('#myForm').ajaxSubmit(options);


ajaxSubmit(object)

ajaxSubmit(object)

ajaxSubmit() provides a mechanism for submitting an HTML form using AJAX. ajaxSubmit accepts a single argument which can be either a success callback function or an options Object. If a function is provided it will be invoked upon successful completion of the submit and will be passed the response from the server. If an options Object is provided, the following attributes are supported: target: Identifies the element(s) in the page to be updated with the server response. This value may be specified as a jQuery selection string, a jQuery object, or a DOM element. default value: null url: URL to which the form data will be submitted. default value: value of form's 'action' attribute method:

返回值

jQuery

参数

  • object (options): literal containing options which control the form submission process

示例

说明:

Submit form and alert server response

jQuery 代码:
$('#myForm').ajaxSubmit(function(data) { alert('Form submit succeeded! Server returned: ' + data); });

说明:

Submit form and update page element with server response

jQuery 代码:
var options = { target: '#myTargetDiv' }; $('#myForm').ajaxSubmit(options);

说明:

Submit form and alert the server response

jQuery 代码:
var options = { success: function(responseText) { alert(responseText); } }; $('#myForm').ajaxSubmit(options);

说明:

Pre-submit validation which aborts the submit operation if form data is empty

jQuery 代码:
var options = { beforeSubmit: function(formArray, jqForm) { if (formArray.length == 0) { alert('Please enter data.'); return false; } } }; $('#myForm').ajaxSubmit(options);

说明:

json data returned and evaluated

jQuery 代码:
var options = { url: myJsonUrl.php, dataType: 'json', success: function(data) { // 'data' is an object representing the the evaluated json data } }; $('#myForm').ajaxSubmit(options);

说明:

XML data returned from server

jQuery 代码:
var options = { url: myXmlUrl.php, dataType: 'xml', success: function(responseXML) { // responseXML is XML document object var data = $('myElement', responseXML).text(); } }; $('#myForm').ajaxSubmit(options);

说明:

submit form and reset it if successful

jQuery 代码:
var options = { resetForm: true }; $('#myForm').ajaxSubmit(options);

说明:

Bind form's submit event to use ajaxSubmit

jQuery 代码:
$('#myForm).submit(function() { $(this).ajaxSubmit(); return false; });


clearForm()

clearForm()

Clears the form data. Takes the following actions on the form's input fields: - input text fields will have their 'value' property set to the empty string - select elements will have their 'selectedIndex' property set to -1 - checkbox and radio inputs will have their 'checked' property set to false - inputs of type submit, button, reset, and hidden will not be effected - button elements will not be effected

返回值

jQuery

示例

说明:

Clears all forms on the page.

jQuery 代码:
$('form').clearForm();


clearInputs()

clearInputs()

Clears the selected form elements. Takes the following actions on the matched elements: - input text fields will have their 'value' property set to the empty string - select elements will have their 'selectedIndex' property set to -1 - checkbox and radio inputs will have their 'checked' property set to false - inputs of type submit, button, reset, and hidden will not be effected - button elements will not be effected

返回值

jQuery

示例

说明:

Clears all inputs with class myInputs

jQuery 代码:
$('.myInputs').clearInputs();


fieldSerialize(true)

fieldSerialize(true)

Serializes all field elements in the jQuery object into a query string. This method will return a string in the format: name1=value1&name2=value2 The successful argument controls whether or not serialization is limited to 'successful' controls (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument is true.

返回值

String

参数

  • true (successful): if only successful controls should be serialized (default is true)

示例

说明:

Collect the data from all successful input elements into a query string

jQuery 代码:
var data = $("input").formSerialize();
说明:

Collect the data from all successful radio input elements into a query string

jQuery 代码:
var data = $(":radio").formSerialize();
说明:

Collect the data from all successful checkbox input elements in myForm into a query string

jQuery 代码:
var data = $("#myForm :checkbox").formSerialize();
说明:

Collect the data from all checkbox elements in myForm (even the unchecked ones) into a query string

jQuery 代码:
var data = $("#myForm :checkbox").formSerialize(false);
说明:

Collect the data from all successful input, select, textarea and button elements into a query string

jQuery 代码:
var data = $(":input").formSerialize();


fieldValue

fieldValue

fieldValue(successful)

Returns the value of the field element in the jQuery object. If there is more than one field element in the jQuery object the value of the first successful one is returned. The successful argument controls whether or not the field element must be 'successful' (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument is true. If this value is false then the value of the first field element in the jQuery object is returned. Note: If no valid value can be determined the return value will be undifined. Note: The fieldValue returned for a select-multiple element or for a checkbox input will always be an array if it is not undefined.

返回值

String or Array<String>

参数

  • successful (Boolean): true if value returned must be for a successful controls (default is true)

示例

说明:

Gets the current value of the myPasswordElement element

jQuery 代码:
var data = $("#myPasswordElement").formValue();
说明:

Get the value of the first successful control in the jQuery object.

jQuery 代码:
var data = $("#myForm :input").formValue();
说明:

Get the array of values for the first set of successful checkbox controls in the jQuery object.

jQuery 代码:
var data = $("#myForm :checkbox").formValue();

说明:

Get the value of the select control

jQuery 代码:
var data = $("#mySingleSelect").formValue();

说明:

Get the array of selected values for the select-multiple control

jQuery 代码:
var data = $("#myMultiSelect").formValue();

fieldValue(el, successful)

Returns the value of the field element. The successful argument controls whether or not the field element must be 'successful' (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The default value of the successful argument is true. If the given element is not successful and the successful arg is not false then the returned value will be null. Note: The fieldValue returned for a select-multiple element will always be an array.

返回值

String or Array<String>

参数

  • el (Element): The DOM element for which the value will be returned
  • successful (Boolean): true if value returned must be for a successful controls (default is true)

示例

说明:

Gets the current value of the myPasswordElement element

jQuery 代码:
var data = jQuery.fieldValue($("#myPasswordElement")[0]);


formSerialize(true)

formSerialize(true)

Serializes form data into a 'submittable' string. This method will return a string in the format: name1=value1&name2=value2 The semantic argument can be used to force form serialization in semantic order. If your form must be submitted with name/value pairs in semantic order then pass true for this arg, otherwise pass false (or nothing) to avoid the overhead for this logic (which can be significant for very large forms).

返回值

String

参数

  • true (semantic): if serialization must maintain strict semantic ordering of elements (slower)

示例

说明:

Collect all the data from a form into a single string

jQuery 代码:
var data = $("#myForm").formSerialize(); $.ajax('POST', "myscript.cgi", data);


formToArray(true)

formToArray(true)

formToArray() gathers form element data into an array of objects that can be passed to any of the following ajax functions: $.get, $.post, or load. Each object in the array has both a 'name' and 'value' property. An example of an array for a simple login form might be: [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] It is this array that is passed to pre-submit callback functions provided to the ajaxSubmit() and ajaxForm() methods. The semantic argument can be used to force form serialization in semantic order. If your form must be submitted with name/value pairs in semantic order then pass true for this arg, otherwise pass false (or nothing) to avoid the overhead for this logic (which can be significant for very large forms).

返回值

Array<Object>

参数

  • true (semantic): if serialization must maintain strict semantic ordering of elements (slower)

示例

说明:

Collect all the data from a form and submit it to the server.

jQuery 代码:
var data = $("#myForm").formToArray(); $.post( "myscript.cgi", data );


resetForm()

resetForm()

Resets the form data. Causes all form elements to be reset to their original value.

返回值

jQuery

示例

说明:

Resets all forms on the page.

jQuery 代码:
$('form').resetForm();


$.recallDroppables()

$.recallDroppables()

Recalculate all Droppables

返回值

jQuery

示例

jQuery 代码:
$.recallDroppable();


$.SortSerialize()

$.SortSerialize()

This function returns the hash and an object (can be used as arguments for $.post) for every sortable in the page or specific sortables. The hash is based on the 'id' attributes of container and items.

返回值

String

参数

  • ():


Draggable(hash)

Draggable(hash)

Create a draggable element with a number of advanced options including callback, Google Maps type draggables, reversion, ghosting, and grid dragging.

返回值

jQuery

参数

  • hash (Hash): A hash of parameters. All parameters are optional.

Hash 选项

  • handle (String): The jQuery selector matching the handle that starts the draggable
  • handle (DOMElement): The DOM Element of the handle that starts the draggable
  • revert (Boolean): When true, on stop-drag the element returns to initial position
  • ghosting (Boolean): When true, a copy of the element is moved
  • zIndex (Integer): zIndex depth for the element while it is being dragged
  • opacity (Float): A number between 0 and 1 that indicates the opacity of the element while being dragged
  • grid (Integer): A number of pixels indicating the grid that the element should snap to
  • grid (Array): A number of x-pixels and y-pixels indicating the grid that the element should snap to
  • fx (Integer): Duration for the effect (like ghosting or revert) applied to the draggable
  • containment (String): Define the zone where the draggable can be moved. 'parent' moves it inside parent element, while 'document' prevents it from leaving the document and forcing additional scrolling
  • containment (Array): An 4-element array (topm left, width, height) indicating the containment of the element
  • axis (String): Set an axis: vertical (with 'vertically') or horizontal (with 'horizontally')
  • onStart (Function): Callback function triggered when the dragging starts
  • onStop (Function): Callback function triggered when the dragging stops
  • onChange (Function): Callback function triggered when the dragging stop and the element was moved at least one pixel
  • onDrag (Function): Callback function triggered while the element is dragged. Receives two parameters: x and y coordinates. You can return an object with new coordinates {x: x, y: y} so this way you can interact with the dragging process (for instance, build your containment)
  • insideParent (Boolean): Forces the element to remain inside its parent when being dragged (like Google Maps)
  • snapDistance (Integer): The element is not moved unless it is dragged more than snapDistance. You can prevent accidental dragging and keep regular clicking enabled (for links or form elements, for instance)
  • cursorAt (Object): The dragged element is moved to the cursor position with the offset specified. Accepts value for top, left, right and bottom offset. Basically, this forces the cursor to a particular position during the entire drag operation.
  • autoSize (Boolean): When true, the drag helper is resized to its content, instead of the dragged element's sizes


DraggableDestroy()

DraggableDestroy()

Destroy an existing draggable on a collection of elements

返回值

jQuery

示例

jQuery 代码:
$('#drag2').DraggableDestroy();


Droppable(options)

Droppable(options)

With the Draggables plugin, Droppable allows you to create drop zones for draggable elements.

参数

  • options (Hash): A hash of options

Hash 选项

  • accept (String): The class name for draggables to get accepted by the droppable (mandatory)
  • activeclass (String): When an acceptable draggable is moved, the droppable gets this class
  • hoverclass (String): When an acceptable draggable is inside the droppable, the droppable gets this class
  • tolerance (String): Choose from 'pointer', 'intersect', or 'fit'. The pointer options means that the pointer must be inside the droppable in order for the draggable to be dropped. The intersect option means that the draggable must intersect the droppable. The fit option means that the entire draggable must be inside the droppable.
  • onDrop (Function): When an acceptable draggable is dropped on a droppable, this callback is called. It passes the draggable DOMElement as a parameter.
  • onHover (Function): When an acceptable draggable is hovered over a droppable, this callback is called. It passes the draggable DOMElement as a parameter.
  • onOut (Function): When an acceptable draggable leaves a droppable, this callback is called. It passes the draggable DOMElement as a parameter.

示例

jQuery 代码:
$('#dropzone1').Droppable( { accept : 'dropaccept', activeclass: 'dropzoneactive', hoverclass: 'dropzonehover', ondrop: function (drag) { alert(this); //the droppable alert(drag); //the draggable }, fit: true } )


DroppableDestroy()

DroppableDestroy()

Destroy an existing droppable on a collection of elements

返回值

jQuery

示例

jQuery 代码:
$('#drag2').DroppableDestroy();


Sortable(options)

Sortable(options)

Allows you to resort elements within a container by dragging and dropping. Requires the Draggables and Droppables plugins. The container and each item inside the container must have an ID. Sortables are especially useful for lists.

参数

  • options (Hash): A hash of options

Hash 选项

  • accept (String): The class name for items inside the container (mandatory)
  • activeclass (String): The class for the container when one of its items has started to move
  • hoverclass (String): The class for the container when an acceptable item is inside it
  • helperclass (String): The helper is used to point to the place where the item will be moved. This is the class for the helper.
  • opacity (Float): Opacity (between 0 and 1) of the item while being dragged
  • ghosting (Boolean): When true, the sortable is ghosted when dragged
  • tolerance (String): Either 'pointer', 'intersect', or 'fit'. See Droppable for more details
  • fit (Boolean): When true, sortable must be inside the container in order to drop
  • fx (Integer): Duration for the effect applied to the sortable
  • onchange (Function): Callback that gets called when the sortable list changed. It takes an array of serialized elements
  • floats (Boolean): True if the sorted elements are floated
  • containment (String): Use 'parent' to constrain the drag to the container
  • axis (String): Use 'horizontally' or 'vertically' to constrain dragging to an axis
  • handle (String): The jQuery selector that indicates the draggable handle
  • handle (DOMElement): The node that indicates the draggable handle
  • onHover (Function): Callback that is called when an acceptable item is dragged over the container. Gets the hovering DOMElement as a parameter
  • onOut (Function): Callback that is called when an acceptable item leaves the container. Gets the leaving DOMElement as a parameter
  • cursorAt (Object): The mouse cursor will be moved to the offset on the dragged item indicated by the object, which takes "top", "bottom", "left", and "right" keys
  • onStart (Function): Callback function triggered when the dragging starts
  • onStop (Function): Callback function triggered when the dragging stops

示例

jQuery 代码:
$('ul').Sortable( { accept : 'sortableitem', activeclass : 'sortableactive', hoverclass : 'sortablehover', helperclass : 'sorthelper', opacity: 0.5, fit : false } )


SortableAddItem(elem)

SortableAddItem(elem)

A new item can be added to a sortable by adding it to the DOM and then adding it via SortableAddItem.

返回值

jQuery

参数

  • elem (DOMElement): A DOM Element to add to the sortable list

示例

jQuery 代码:
$('#sortable1').append('<li id="newitem">new item</li>') .SortableAddItem($("#new_item")[0])


$.meta.setType(type, name)

$.meta.setType(type, name)

Sets the type of metadata to use. Metadata is encoded in JSON, and each property in the JSON will become a property of the element itself. There are three supported types of metadata storage: attr: Inside an attribute. The name parameter indicates which attribute. class: Inside the class attribute, wrapped in curly braces: { } elem: Inside a child element (e.g. a script tag). The name parameter indicates which element. The metadata for an element is loaded the first time the element is accessed via jQuery. As a result, you can define the metadata type, use $(expr) to load the metadata into the elements matched by expr, then redefine the metadata type and run another $(expr) for other elements.

返回值

undefined

参数

  • type (String): The encoding type
  • name (String): The name of the attribute to be used to get metadata (optional)

示例

说明:

Reads metadata from the class attribute

HTML 代码:
$.meta.setType("class")
jQuery 代码:
<p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>

说明:

Reads metadata from a "data" attribute

HTML 代码:
$.meta.setType("attr", "data")
jQuery 代码:
<p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>

说明:

Reads metadata from a nested script element

HTML 代码:
$.meta.setType("elem", "script")
jQuery 代码:
<p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>


data()

data()

Returns the metadata object for the first member of the jQuery object.

返回值

jQuery


disableTab(position)

disableTab(position)

Disable a tab, so that clicking it has no effect.

返回值

jQuery

参数

  • position (Number): An integer specifying the position of the tab (no zero-based index) to be disabled. If this parameter is omitted, the first tab will be disabled.

示例

说明:

Disable the second tab of the tab interface contained in <div id="container">.

jQuery 代码:
$('#container').disableTab(2);


enableTab(position)

enableTab(position)

Enable a tab that has been disabled.

返回值

jQuery

参数

  • position (Number): An integer specifying the position of the tab (no zero-based index) to be enabled. If this parameter is omitted, the first tab will be enabled.

示例

说明:

Enable the second tab of the tab interface contained in <div id="container">.

jQuery 代码:
$('#container').enableTab(2);


tabs(initial, settings)

tabs(initial, settings)

Create an accessible, unobtrusive tab interface based on a certain HTML structure. The underlying HTML has to look like this: <div id="container"> <ul> <li><a href="#section-1">Section 1</a></li> <li><a href="#section-2">Section 2</a></li> <li><a href="#section-3">Section 3</a></li> </ul> <div id="section-1"> </div> <div id="section-2"> </div> <div id="section-3"> </div> </div> Each anchor in the unordered list points directly to a section below represented by one of the divs (the URI in the anchor's href attribute refers to the fragment with the corresponding id). Because such HTML structure is fully functional on its own, e.g. without JavaScript, the tab interface is accessible and unobtrusive. A tab is also bookmarkable via hash in the URL. Use the History/Remote plugin (Tabs will auto-detect its presence) to fix the back (and forward) button.

返回值

jQuery

参数

  • initial (Number): An integer specifying the position of the tab (no zero-based index) that gets first activated, e.g. on page load. If a hash in the URL of the page refers to one fragment (tab container) of a tab interface, this parameter will be ignored and instead the tab belonging to that fragment in that specific tab interface will be activated. Defaults to 1 if omitted.
  • settings (Object): An object literal containing key/value pairs to provide optional settings.

Hash 选项

  • disabled (Array<Number>): An array containing the position of the tabs (no zero-based index) that should be disabled on initialization. Default value: null.
  • bookmarkable (Boolean): Boolean flag indicating if support for bookmarking and history (via changing hash in the URL of the browser) is enabled. Default value: false, unless the History/Remote plugin is included. In that case the default value becomes true. @see $.ajaxHistory.initialize
  • fxFade (Boolean): Boolean flag indicating whether fade in/out animations are used for tab switching. Can be combined with fxSlide. Will overrule fxShow/fxHide. Default value: false.
  • fxSlide (Boolean): Boolean flag indicating whether slide down/up animations are used for tab switching. Can be combined with fxFade. Will overrule fxShow/fxHide. Default value: false.
  • fxSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds (e.g. 1000) to run an animation. Default value: "normal".
  • fxShow (Object): An object literal of the form jQuery's animate function expects for making your own, custom animation to reveal a tab upon tab switch. Unlike fxFade or fxSlide this animation is independent from an optional hide animation. Default value: null. @see animate
  • fxHide (Object): An object literal of the form jQuery's animate function expects for making your own, custom animation to hide a tab upon tab switch. Unlike fxFade or fxSlide this animation is independent from an optional show animation. Default value: null. @see animate
  • fxShowSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds (e.g. 1000) to run the animation specified in fxShow. Default value: fxSpeed.
  • fxHideSpeed (String|Number): A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds (e.g. 1000) to run the animation specified in fxHide. Default value: fxSpeed.
  • fxAutoHeight (Boolean): Boolean flag that if set to true causes all tab heights to be constant (being the height of the tallest tab). Default value: false.
  • onClick (Function): A function to be invoked upon tab switch, immediatly after a tab has been clicked, e.g. before the other's tab content gets hidden. The function gets passed three arguments: the first one is the clicked tab (e.g. an anchor element), the second one is the DOM element containing the content of the clicked tab (e.g. the div), the third argument is the one of the tab that gets hidden. Default value: null.
  • onHide (Function): A function to be invoked upon tab switch, immediatly after one tab's content got hidden (with or without an animation) and right before the next tab is revealed. The function gets passed three arguments: the first one is the clicked tab (e.g. an anchor element), the second one is the DOM element containing the content of the clicked tab, (e.g. the div), the third argument is the one of the tab that gets hidden. Default value: null.
  • onShow (Function): A function to be invoked upon tab switch. This function is invoked after the new tab has been revealed, e.g. after the switch is completed. The function gets passed three arguments: the first one is the clicked tab (e.g. an anchor element), the second one is the DOM element containing the content of the clicked tab, (e.g. the div), the third argument is the one of the tab that gets hidden. Default value: null.
  • selectedClass (String): The CSS class attached to the li element representing the currently selected (active) tab. Default value: "tabs-selected".
  • disabledClass (String): The CSS class attached to the li element representing a disabled tab. Default value: "tabs-disabled".
  • hideClass (String): The CSS class used for hiding inactive tabs. A class is used instead of "display: none" in the style attribute to maintain control over visibility in other media types than screen, most notably print. Default value: "tabs-hide".
  • tabStruct (String): A CSS selector or basic XPath expression reflecting a nested HTML structure that is different from the default single div structure (one div with an id inside the overall container holds one tab's content). If for instance an additional div is required to wrap up the several tab containers such a structure is expressed by "div>div". Default value: "div".

示例

说明:

Create a basic tab interface.

jQuery 代码:
$('#container').tabs();

说明:

Create a basic tab interface with the second tab initially activated.

jQuery 代码:
$('#container').tabs(2);

说明:

Create a tab interface with the third and fourth tab being disabled.

jQuery 代码:
$('#container').tabs({disabled: [3, 4]});

说明:

Create a tab interface that uses slide down/up animations for showing/hiding tab content upon tab switching.

jQuery 代码:
$('#container').tabs({fxSlide: true});


triggerTab(position)

triggerTab(position)

Activate a tab programmatically with the given position (no zero-based index), as if the tab itself were clicked.

返回值

jQuery

参数

  • position (Number): An integer specifying the position of the tab (no zero-based index) to be activated. If this parameter is omitted, the first tab will be activated.

示例

说明:

Activate the second tab of the tab interface contained in <div id="container">.

jQuery 代码:
$('#container').triggerTab(2);

说明:

Activate the first tab of the tab interface contained in <div id="container">.

jQuery 代码:
$('#container').triggerTab(1);

说明:

Activate the first tab of the tab interface contained in <div id="container">.

jQuery 代码:
$('#container').triggerTab();


Tooltip(settings)

Tooltip(settings)

Display a customized tooltip instead of the default one for every selected element. The tooltip behaviour mimics the default one, but lets you style the tooltip and specify the delay before displaying it. In addition, it displays the href value, if it is available. To style the tooltip, use these selectors in your stylesheet: #tooltip - The tooltip container #tooltip h3 - The tooltip title #tooltip p.body - The tooltip body, shown when using showBody #tooltip p.url - The tooltip url, shown when using showURL

返回值

jQuery

参数

  • settings (Object): (optional) Customize your Tooltips

Hash 选项

  • delay (Number): The number of milliseconds before a tooltip is display, default is 250
  • event (String): The event on which the tooltip is displayed, default is "mouseover", "click" works fine, too
  • track (Boolean): If true, let the tooltip track the mousemovement, default is false
  • showURL (Boolean): If true, shows the href or src attribute within p.url, default is true
  • showBody (String): If specified, uses the String to split the title, displaying the first part in the h3 tag, all following in the p.body tag, separated with <br/>s, default is null
  • extraClass (String): If specified, adds the class to the tooltip helper, default is null
  • fixPNG (Boolean): If true, fixes transparent PNGs in IE, default is false

示例

说明:

Shows tooltips for anchors, inputs and images, if they have a title

jQuery 代码:
$('a, input, img').Tooltip();
说明:

Shows tooltips for labels with no delay, tracking mousemovement, displaying the tooltip when the label is clicked.

jQuery 代码:
$('label').Tooltip({ delay: 0, track: true, event: "click" });
说明:

This example starts with modifying the global settings, applying them to all following Tooltips; Afterwards, Tooltips for anchors with class pretty are created with an extra class for the Tooltip: "fancy" for anchors, "fancy-img" for images

jQuery 代码:
// modify global settings $.extend($.fn.Tooltip.defaults, { track: true, delay: 0, showURL: false, showBody: " - ", fixPNG: true }); // setup fancy tooltips $('a.pretty').Tooltip({ extraClass: "fancy" }); $('img.pretty').Tooltip({ extraClass: "fancy-img", });