jquery链式语法

版权声明:分享才能获得最大的价值 https://blog.csdn.net/qq_32252957/article/details/86557324

虽然jquery已经被淘汰了,但是我想通过快速学习jquery了解其优点和缺点,一方面锻炼自己的学习能力,一方面对其设计哲学和设计理念进行探索.面对前端框架快速变化的时代背景下,我们还是沉下心好好分析内部的工作方式吧,而不仅仅在于表象


链式语法:
因为 jQuery 库的缘故,链式语法在前端界变得非常流行。实际上这是一种非常容易实现的模式。基本上,你只需要让每个函数返回 ‘this’,这样其他函数就可以立即被调用。
eg:

var bird = {
    catapult: function() {
        console.log( "Yippeeeeee!" );
        return this;
    },
    destroy: function() {
        console.log( "That'll teach you... you dirty pig!" );
        return this;
    }
};
bird.catapult().destroy();

链式语法的优缺点:
节约JS代码;所返回的都是同一个对象,可以提高代码的效率.(jquery的设计哲学是Write less, do more).

我们举个使用jquery库的例子;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>chaining</title>
    <style>
        body{
            font-size: 30px;
        }

        .blue{
            color: blue;
        }

        .bold{
            font-size: 40px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div id="divTest" class="blue">
        test
    </div>
    <div id="divTest2">
        <p>123</p>
        <p class="child">123</p>
        <p>123</p>
    </div>

    <script src="../../vendor/jquery-1.12.4.js"></script>
    <script>
        setTimeout(function(){
            // $('#divTest').text('Hello, world!');
            // $('#divTest').removeClass('blue');
            // $('#divTest').addClass('bold');
            // $('#divTest').css('color', 'red');

            $('#divTest').text("hello, world!")
            .removeClass('blue')
            .addClass('bold')
            .css('color', 'red');

            $('#divTest2').get(0)
                .find('p.child')
                .css('color', 'red')
                .end()
                .addClass('bold');
        }, 2000);
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_32252957/article/details/86557324
今日推荐