end()
终止在当前链的最新过滤操作,并返回匹配的元素的以前状态。
.end()
- 这个方法不接受任何参数。
大多数 jQueryDOM遍历方法来操作 jQuery 对象实例,并创建一个新的对象,匹配一个不同的 DOM 元素集合。当发生这种情况时,实际上是新的元素集合被压入到对象内部维护的栈中。每次过滤方法都会被压入栈中。当我们需要返回到前一个状态时,我们可以使用end()进行出栈操作,来返回栈中的前一个状态。
假设页面上有几个短的列表
<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>
end()方法主要用于 jQuery 的链式属性中。当没有使用链式用法时,我们通常只是调用变量名上的前一个对象,所以我们不需要操作栈。使用end()时,我们可以一次性调用所有需要的方法:
$('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 个列表项的背景色有颜色,而第二个列表中的任何项目都没有背景色。
- list item 1
- list item 2
- list item 1
- list item 2
对于一个长的 jQuery 链式写法,可以使用结构块的写法,让其具有很好的可读性,即:将end()方法与其对应的过滤方法写在一个嵌套块中,例如:
$('ul.first').find('.foo')
.css('background-color', 'red')
.end().find('.bar')
.css('background-color', 'green')
.end();
最后的end()是不必要的,我们丢弃紧随其后的jQuery对象。然而,当编写这种形式的代码,end()提供了可视化的对称性和完整性,至少一些开发者的眼中,更具可读性,这样存在一些性能成本,因为它是一个额外的函数调用。
例子
选择所有的段落,在其中查找 span 元素,之后再恢复到选择段落的状态。
<!DOCTYPE html>
<html>
<head>
<style>
p, div { margin:1px; padding:1px; font-weight:bold;
font-size:16px; }
div { color:blue; }
b { color:red; }
</style>
<script src="https://www.lanmper.cn/static/js/jquery-3.5.0.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>
Hi there how are you doing?
This span is one of several spans in this sentence.
选择所有段落,在这些段落中查找范围元素,并将所选内容还原回段落。
<!DOCTYPE html>
<html>
<head>
<style>p { margin:10px; padding:10px; }</style>
<script src="https://www.lanmper.cn/static/js/jquery-3.5.0.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>
Hello, how are you?
