• jQuery入门[4]-链式代码


    jQuery另一个很令人惬意的地方是,一般的代码都是一行一行写,jQuery的代码可以一串一串写。
    这一点,在前面的文章中已经介绍过了。
    直接来一个Demo:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        
    <title>chainning code</title>
        
    <script src="../scripts/jquery-1.2.3.intellisense.js" type="text/javascript"></script>
        
    <script type="text/javascript">
            $(
    function(){
                
    //添加四个按钮
                $('<input type="button" value="click me"/><input type="button" value="triggle click me"/><input type="button" value="detach handler"/><input type="button" value="show/hide text"/>').appendTo($('body'));
                
    //找出所有按钮
                $('input[type="button"]')
                    .eq(
    0)//找到第一个按钮
                        .click(function(){
                            alert(
    'you clicked me!');
                        })
                    .end().eq(
    1)//返回所有按钮,再找到第二个
                        .click(function(){
                            $(
    'input[type="button"]:eq(0)').trigger('click');
                        })
                    .end().eq(
    2)//返回所有按钮,再找到第三个
                        .click(function(){
                            $(
    'input[type="button"]:eq(0)').unbind('click');
                        })
                    .end().eq(
    3)//返回所有按钮,再找到第四个
                        .toggle(function(){
                            $(
    '.panel').hide('slow');
                        },
    function(){
                            $(
    '.panel').show('slow');
                        });
            });
        
    </script>
        
    <style type="text/css">
            .panel
            
    {
                padding
    : 20px;
                background-color
    : #000066;
                color
    : #FFFFFF;
                font-weight
    : bold;
                width
    : 200px;
                height
    : 50px;
            
    }
        
    </style>
    </head>
    <body>
        
    <div class="panel">welcome to jQuery!</div>
    </body>
    </html>


    现在,链式代码已经成为jQuery非常流行的一个特点了,在使用链条方式写代码时,可能会用到eq()/filter()……(reference:http://docs.jquery.com/Traversing)等方法变化jQuery对象的对应范围,然后,又可以用end()函数将范围复原到原来的状况。
    需要注意的是,有几个函数并不返回jQuery对象,所以链条就不能继续下去,比如get()就不能像eq()那样用。
  • 相关阅读:
    Timer定时任务
    spring boot配置多数据源
    消费者模块调用提供者集群报错
    修改windHost文件
    spring常用注解+Aop
    添加ClustrMaps
    无题
    2020年3月21日 ICPC训练联盟周赛,Benelux Algorithm Programming Contest 2019
    2020年3月14日 ICPC训练联盟周赛,Preliminaries for Benelux Algorithm Programming Contest 2019
    2020.4.12 个人rating赛 解题+补题报告
  • 原文地址:https://www.cnblogs.com/callbin/p/1437311.html
Copyright © 2020-2023  润新知