jQuery中的end()方法

xiaoxiao2025-11-08  4

.end()返回: jQuery 描述: 终止在当前链的最新过滤操作,并返回匹配的元素的以前状态。

添加的版本: 1.0.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() 将只会查找

中的 ‘.bar’,而不是继续在 中进行查找,结果是将匹配到的元素的背景色变成绿色。上述代码的最终结果是,第一个列表中的第 1 和第 3 个列表项的背景色有颜色,而第二个列表中的任何项目都没有背景色。

对于一个长的 jQuery 链式写法,可以使用结构块的写法,让其具有很好的可读性,即:将 end() 方法与其对应的过滤方法写在一个嵌套块中,例如:

$('ul.first').find('.foo') .css('background-color', 'red') .end().find('.bar') .css('background-color', 'green') .end();

最后的end()是不必要的,我们丢弃紧随其后的jQuery对象。然而,当编写这种形式的代码,end()提供了可视化的对称性和完整性,至少一些开发者的眼中,更具可读性,这样存在一些性能成本,因为它是一个额外的函数调用。

例子: Example: 选择所有的段落,在其中查找 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="http://code.jquery.com/jquery-latest.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>

Demo:

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

Demo:

转载请注明原文地址: https://www.6miu.com/read-5039259.html

最新回复(0)