0

我查看了函数 end() 的 jquery 文档,

定义:结束当前链中最近的过滤操作,并将匹配的元素集合返回到其先前的状态。

我已经理解了这个功能,但我无法弄清楚它在哪里更有帮助。

前任:

<p>text</p>
<p class="middle">Middle <span>text</span></p>
<p>text</p>

<script type="text/JavaScript">
alert(jQuery('p').filter('.middle').length); //alerts 1
alert(jQuery('p').filter('.middle').end().length); //alerts 3
alert(jQuery('p').filter('.middle').find('span')
</script>

我已经理解了第二行显示//alerts 3,但它也可以写成

 alert(jQuery('p').length); //alerts 3

那为什么要额外的两个方法.filter.end()

请给我一个例子,其中 .end() 将很有用。

4

1 回答 1

0

HTML

<p>text</p>
<p class="middle">Middle <span>text</span></p>
<p>text</p>

在这个 p 标签中作为兄弟元素

并且 pwith class "middle" 有子标签,即 "span" 标签

现在谈谈你的js

     <script type="text/JavaScript">

        /*it display 1 and its right first we find p tag then in this we filter by "middle class" 
        and in p tag only one have this class so alert  1
       */
 alert(jQuery('p').filter('.middle').length); 

       /*it display 3 and its right first we find p tag then in this we filter by "middle class" then again use end inn jquery then it again goes to previous selector means  
    (jQuery('p').filter('.middle') to jQuery('p') 

    so it alert 3
                  */
 alert(jQuery('p').filter('.middle').end().length); //alerts 3

    /*it display 3 and its right first we find p tag then in this we filter by "middle class" then again use find span and it has one span in middle class so it alert 1

   */ 
        alert(jQuery('p').filter('.middle').find('span').length); alert 1
        </script>

参考

寻找

筛选

于 2013-08-26T06:51:22.200 回答