.end()

.end()返回类型:jQuery

描述:结束当前连缀中最近的筛选操作,并把匹配的元素集合返回到它的上一个状态。

  • 增补版本:1.0.end()

    • 此方法不接受任何参数。

大多数jQuery的文档处理方法在jQuery对象实例上进行操作,产生一个新的实例,匹配不同的DOM元素集合。做这时,就像新的元素集合推加到保留在对象内部的一个堆栈上。每个连续的筛选方法把新元素集合推加到堆栈上。如果我们需要旧元素集合,我们可以使用end()把集合从堆栈中取出。

假设我们需要网页上的一对简写列表:

1
2
3
4
5
6
7
8
9
10
<ul class="first">
<li class="foo">list item 1</li>
<li>list item 2</li>
<li class="bar">list item 3</li>
</ul>
<ul class="second">
<li class="foo">list item 1</li>
<li>list item 2</li>
<li class="bar">list item 3</li>
</ul>

在开拓jQuery的连缀属性时,.end()方法相当有用。如果不使用连缀,我们可以通常通过变量名称来调用一个先前的对象,所以我们不需要操纵堆栈。然而,利用.end(),我们可以把方法调用串联起来:

1
2
3
4
5
6
$( "ul.first" )
.find( ".foo" )
.css( "background-color", "red" )
.end()
.find( ".bar" )
.css( "background-color", "green" );

针对带有类foo项目的这种连缀搜索,只在第一个列表里面,然后把它们的背景变成红色。然后.end()把对象返回到调用.find()以前的状态,所以第二个.find()<ul class="first">里面搜索 '.bar',而不是在列表的<li class="foo">里面搜索,把匹配的元素的背景变成绿色。结果是第一个列表中的项目1和3带有着色背景,而第二个列表中没有一项被着色。

一个长的jQuery连缀可被视为结构化代码块,筛选方法提供了嵌套块的打开,而.end()方法关闭了它们。

1
2
3
4
5
6
7
$( "ul.first" )
.find( ".foo" )
.css( "background-color", "red" )
.end()
.find( ".bar" )
.css( "background-color", "green" )
.end();

最后的.end()是不必要的,因为我们随后丢弃了该jQuery对象。然而,如果代码用这种形式写,.end()提供了视觉对称以及和完整性——至少在开发者眼中,使程序更具有可读性,这样存在一些性能成本,因为它是一个额外的函数调用。

示例:

选择所有的段落,找到它里面的<span>元素,并把这些选区翻转之后倒回段落。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>end demo</title>
<style>
p, div {
margin: 1px;
padding: 1px;
font-weight: bold;
font-size: 16px;
}
div {
color: blue;
}
b {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>
Hi there <span>how</span> are you <span>doing</span>?
</p>
<p>
This <span>span</span> is one of
several <span>spans</span> in this
<span>sentence</span>.
</p>
<div>
Tags in jQuery object initially: <b></b>
</div>
<div>
Tags in jQuery object after find: <b></b>
</div>
<div>
Tags in jQuery object after end: <b></b>
</div>
<script>
jQuery.fn.showTags = function( n ) {
var tags = this.map(function() {
return this.tagName;
})
.get()
.join( ", " );
$( "b:eq( " + n + " )" ).text( tags );
return this;
};
$( "p" )
.showTags( 0 )
.find( "span" )
.showTags( 1 )
.css( "background", "yellow" )
.end()
.showTags( 2 )
.css( "font-style", "italic" );
</script>
</body>
</html>

演示:

选择所有的段落,找到它里面的<span>,翻转选区再放回段落。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>end demo</title>
<style>
p {
margin: 10px;
padding: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p><span>Hello</span>, how are you?</p>
<script>
$( "p" )
.find( "span" )
.end()
.css( "border", "2px red solid" );
</script>
</body>
</html>

演示: