• jquery end() 方法


    The end( ) method reverts the most recent destructive operation, changing the set of matched elements to its previous state right before the destructive operation.

    Syntax:

    Here is the simple syntax to use this method:

    operations.end( )
    jQuery文档是这样解释的:jQuery回到最近的一个"破坏性"操作之前。即,将匹配的元素列表变为前一次的状态。

    <div id="test"><h1>jQuery end()方法</h1><p>讲解jQuery中end()方法。</p></div>
    $(document).ready(function() {
        $("#test").click(function() {
            $(this).find("p").hide().end().hide();
        });
    });

    点击id为test的div时,首先找到div里边的p标签,将其隐藏。接下来使用end()方法结束了对p标签的引用,此时返回的是#test(jQuery对象),从而后边的hide()方法隐藏了div。

    详细说明

    大多数 jQuery 的遍历方法会操作一个 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>
    主要是在利用 jQuery 的链条属性(命令链)时,jQuery 会比较有用。如果不使用命令链,我们一般是通过变量名来调用之前的对象,这样我们就不需要操作堆栈了。不过通过 end(),我们可以把所有方法调用串联在一起:
    $('ul.first').find('.foo').css('background-color', 'red')
      .end().find('.bar').css('background-color', 'green');

    这条长长的 jQuery 链可以可视化为结构化的代码块,筛选方法打开嵌套代码块,而 end() 方法用来关闭代码块:

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

    亲自试一试

    最后这个 end() 不是必需的,因为我们随后会丢弃这个 jQuery 对象。不过,如果按照这种形式编写代码,end() 就能提供视觉上的对称,以及规整程序的感觉,至少对于开发者来说更易阅读,当然代价则是由于进行了额外的调用,会有一点点性能损失。

    via:http://www.w3school.com.cn/jquery/traversing_end.asp

    
    
  • 相关阅读:
    闭包
    内置函数
    595926265989859
    C错题集锦
    C中改变指针的指向
    /dev/zero
    define的高级用法
    (转)Linux ./configure --prefix命令
    (转)linux下tty,控制台,虚拟终端,串口,console(控制台终端)详解
    内核驱动模块的Makefile模板
  • 原文地址:https://www.cnblogs.com/youxin/p/2981709.html
Copyright © 2020-2023  润新知