【问题标题】:jQuery end(), where exactly it is usefuljQuery end(),它到底在哪里有用
【发布时间】:2013-08-26 06:39:48
【问题描述】:

我查看了函数 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() 会很有用。

【问题讨论】:

  • 你看过文档吗?它为您提供了示例。
  • @Blender,伙计,我已经看过并理解了它的用途,但正如我所说,对我来说它看起来并不那么重要
  • &lt;p class="middle"&gt;&lt;span class="i1"&gt;Middle&lt;/span&gt; &lt;span class="i2"&gt;text&lt;/span&gt;&lt;/p&gt; 为例,然后 $('p').filter('.middle').find('.i1').css('color', 'red').end ().find('.i2').css('color', 'green')` plnkr.co/edit/tNWZM5lbWHiqjqQkJ7Yj?p=preview

标签: jquery business-logic jquery-end


【解决方案1】:

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>

参考end

find

filter

【讨论】:

    猜你喜欢
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 2011-09-19
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 2018-08-25
    相关资源
    最近更新 更多