什么是jQuery中的链式
在jQuery中,链允许我们在一个单一的语句中对一个元素进行多个操作。
大部分的jQuery函数都会返回一个jQuery对象,由于这个原因,当第一个方法完成执行时,它返回一个obj,现在第二个方法将在这个对象上调用。
例子1:在链式的帮助下,我们可以简洁地开发我们的代码。链式也使我们的脚本更快,因为现在浏览器不必再去寻找相同的元素来对它们进行操作。‘gfg’对象的每个方法都在返回一个对象。
首先,调用geek()方法,然后调用write()方法,然后调用destroy()方法。
<!DOCTYPE html>
<head>
  <script src=
      "https://code.jquery.com/jquery-git.js">
  </script>
</head>
  
<body>
    <script>
        let gfg = {
            geek: function(){
                alert('called geek method');
                return gfg;
            },
            write: function(){
                alert('called write method');
                return gfg;
            },
            destroy: function(){
                alert('called destroy method');
                return gfg;
            }
        }
  
        gfg.geek().write().destroy();
    </script>
</body>
  
</html>
输出:

例子2:下面的代码演示了fadeOut()和fadeIn() 方法的连锁反应。每当你点击按钮时,文本将首先淡出,然后淡入。
<!DOCTYPE html>
<head>
    <!-- jQuery library -->
    <script src="https://code.jquery.com/jquery-git.js"></script>
</head>
  
<body>
    <p id="first">GeeksForGeeks</p>
  
    <button>click me</button>
    <script>
        (document).ready(function(){
            ('button').click(function(){
                $('#first').fadeOut(100).fadeIn(100);
            })
        })
    </script>
</body>
  
</html>
输出:

极客教程