返回值:jQueryend()

结束当前链式方法中,最近使用的过滤操作,并返回匹配元素的前一个状态。

大多数 jQuery DOM 遍历 方法来操作 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 个列表项的背景色有颜色,而第二个列表中的任何项目都没有背景色。

对于一个长的 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="jquery.min.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 元素,之后再恢复到选择段落的状态。

<!DOCTYPE html>
<html>
<head>
<style>p { margin:10px; padding:10px; }</style>
<script src="jquery.min.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>

演示: