jQuery()

返回匹配元素的集合,要么是在DOM中基于传入的参数找到的,要么是通过传入一个HTML字符串创建的。

jQuery( selector [, context ] )返回类型:jQuery

描述:接受一个字符串,包含一个CSS选择器,它可以用来匹配一些元素。

在上面列出的第一个方程式中,jQuery()(它也可以写为$())针对提供的选择器,搜索遍了DOM,以找到匹配它的任何元素,创建了新的jQuery对象,引用这些元素:

1
$( "div.foo" );

如果没有元素匹配提供的选择器,则新的jQuery对象是“空的”,也就是说,它不包含元素,具有属性.length为0。

选择器上下文

默认情况下,选择器在DOM内部实施它们的搜索,从文档根节点开始。然而,可以视情况向$()函数提供第二个参数,从而给出一个替代的上下文,用来搜索。例如,为了在一个事件处理函数内部搜索,搜索可以限定为:

1
2
3
$( "div.foo" ).click(function() {
$( "span", this ).addClass( "bar" );
});

如果针对span选择器的搜索被限制为this上下文,则只有被点击的元素内部的span元素得到附加类。

.find()方法内部实现了选择器上下文,所以$( "span", this )等同于$( this ).find( "span" )

使用DOM元素

此函数的第二个和第三个方程,用一个或多个已经用其它方法选中的DOM元素创建了一个jQuery对象。jQuery对象创建自数组元素,为了让它们追加到数组中;不像大多数其它多元素jQuery操作,这些元素不是按DOM中的顺序排序的。将从数组中复制元素,如果它们已经是jQuery集合,则不会被解包。

请注意,虽然你可以用这种方式把文本节点和注释节点传入到jQuery集合中,但是大多数操作不支持它们。极少数的支持的操作,会在它们的API文档页面中有明确的注明。

单个DOM元素结构的一个常见用法是在一个元素上调用jQuery方法,通过关键字this传递给一个回调函数:

1
2
3
$( "div.foo" ).click(function() {
$( this ).slideUp();
});

此示例在元素被点击时,导致元素以一个滑动动画隐藏起来。因为处理函数在this关键字中接收了被点击的项,作为裸露的DOM元素,所以在应用jQuery方法之前,此元素必须被传递给$()函数。

返回自Ajax调用的XML数据可以传递给$()函数,从而XML结构中的单个元素可以利用.find()和其它DOM遍历方法来检索。

1
2
3
$.post( "url.xml", function( data ) {
var $child = $( data ).find( "child" );
});

克隆jQuery对象

当jQuery对象传递给$()函数时,创建了一个克隆的对象。新的jQuery对象引用了相同的DOM元素,作为初始元素。

返回一个空集

自从jQuery 1.4以来,不带参数地调用jQuery()方法,将返回一个空jQuery集合(.length属性为零)。在先前的jQuery版本中,这将返回一个集合,包含了文档节点。

操作扁平对象

目前,在jQuery中支持扁平JavaScript对象包装的几个对象是:.data().prop().on().off().trigger().triggerHandler()。在扁平对象上使用.data()(或任何需要.data()的方法),将产生对象上的新属性,称为jQuery{randomNumber}(例如:jQuery123456789)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Define a plain object
var foo = { foo: "bar", hello: "world" };
// Pass it to the jQuery function
var $foo = $( foo );
// Test accessing property values
var test1 = $foo.prop( "foo" ); // bar
// Test setting property values
$foo.prop( "foo", "foobar" );
var test2 = $foo.prop( "foo" ); // foobar
// Test using .data() as summarized above
$foo.data( "keyName", "someValue" );
console.log( $foo ); // will now contain a jQuery{randomNumber} property
// Test binding an event name and triggering
$foo.on( "eventName", function () {
console.log( "eventName was called" );
});
$foo.trigger( "eventName" ); // Logs "eventName was called"

应该使用.trigger( "eventName" ),它将在对象上搜索一个“eventName”属性,并尝试在任何附加的jQuery处理函数已经执行了之后执行它。它并不检查属性是不是一个函数。若要避免这种行为,应使用.triggerHandler( "eventName" )来代替。

1
$foo.triggerHandler( "eventName" ); // Also logs "eventName was called"

示例:

找到所有作为<div>元素的子元素的<p>元素,然后对它们应用一个边框。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>one</p>
<div><p>two</p></div>
<p>three</p>
<script>
$( "div > p" ).css( "border", "1px solid gray" );
</script>
</body>
</html>

演示:

在文档中第一个表单里找到所有单选钮类型的输入控件。

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

在一个来自Ajax响应的XML文档的内部,找到所有的div元素。

1
$( "div", xml.responseXML );

把网页的背景色设置为黑色。

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

把表单内部所有的输入元素都隐藏起来。

1
$( myForm.elements ).hide();

jQuery( html [, ownerDocument ] )返回类型:jQuery

描述:根据提供的HTML字符串,快速创建DOM元素。

创建新元素

如果一个字符串传递为$()的参数,则jQuery会检查此字符串以了解它是否看起来像是HTML(例如,它以<tag ... >开头)。如果不是,该字符串被翻译成一个选择器表达式。但是如果字符串看起来像是一个HTML片段,jQuery会尝试创建新的DOM元素,如该HTML所描述的。然后创建了一个jQuery对象,并返回引用到这些元素的对象。你可以在此对象上实施任何常见的jQuery方法:

1
$( "<p id='test'>My <em>new</em> text</p>" ).appendTo( "body" );

For explicit parsing of a string to HTML, use the $.parseHTML() method.

By default, elements are created with an .ownerDocument matching the document into which the jQuery library was loaded. Elements being injected into a different document should be created using that document, e.g., $("<p>hello iframe</p>", $("#myiframe").prop("contentWindow").document).

If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's .innerHTML mechanism. In most cases, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag (with optional closing tag or quick-closing) — $( "<img />" ) or $( "<img>" ), $( "<a></a>" ) or $( "<a>" ) — jQuery creates the element using the native JavaScript .createElement() function.

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

Filtering isn't, however, limited to these tags. For example, Internet Explorer prior to version 8 will also convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:

1
$( "<a href='http://jquery.com'></a>" );

Tags that cannot contain elements may be quick-closed or not:

1
2
$( "<img>" );
$( "<input>" );

When passing HTML to jQuery(), note that text nodes are not treated as DOM elements. With the exception of a few methods (such as .content()), they are generally ignored or removed. E.g:

1
2
var el = $( "<br>2<br>3" ); // returns [<br>, "2", <br>]
el = $( "<br>2<br>3 >" ); // returns [<br>, "2", <br>, "3 &gt;"]

This behavior is expected. As of jQuery 1.9.0 (and unless using the jQuery Migrate plugin), jQuery() requires the HTML string to start with a < (i.e text nodes cannot appear at the front of the HTML string).

As of jQuery 1.4, the second argument to jQuery() can accept a plain object consisting of a superset of the properties that can be passed to the .attr() method.

Important: If the second argument is passed, the HTML string in the first argument must represent a simple element with no attributes. As of jQuery 1.4, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset.

As of jQuery 1.8, any jQuery instance method (a method of jQuery.fn) can be used as a property of the object passed to the second parameter:

1
2
3
4
5
6
7
8
$( "<div></div>", {
"class": "my-div",
on: {
touchstart: function( event ) {
// Do something
}
}
}).appendTo( "body" );

The name "class" must be quoted in the object since it is a JavaScript reserved word, and "className" cannot be used since it refers to the DOM property, not the attribute.

While the second argument is convenient, its flexibility can lead to unintended consequences (e.g. $( "<input>", {size: "4"} ) calling the .size() method instead of setting the size attribute). The previous code block could thus be written instead as:

1
2
3
4
5
6
7
8
$( "<div></div>" )
.addClass( "my-div" )
.on({
touchstart: function( event ) {
// Do something
}
})
.appendTo( "body" );

示例:

Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup.

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

创建一些DOM元素。

1
2
3
4
5
6
7
8
$( "<div/>", {
"class": "test",
text: "Click me!",
click: function() {
$( this ).toggleClass( "test" );
}
})
.appendTo( "body" );

jQuery( callback )返回类型:jQuery

描述:绑定一个要在DOM完成载入时执行的函数。

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. While this function is, technically, chainable, there really isn't much use for chaining against it.

示例:

当DOM准备就绪时,执行函数。

1
2
3
$(function() {
// Document is ready
});

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

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