jQuery 链式编程

261 阅读1分钟

链式编程的格式

链式编程就是不停的调用方法

  • 对象.方法().方法.方法().方法()...
  • 对象调用方法,如果返回值还是当前这个对象,那么就可以继续的调用方法 ⚠️提示: 在jQuery中,一般情况,对象调用的方法,这个方法的意思是设置的意思,那么返回来的几乎都是当前的对象,就可以继续的链式编程了
<input type="button" value="按钮" id="btn">

<script src="https://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
<script>
  $("#btn").click(function () {
    // 获取按钮的value属性
    console.log($(this).val())
    $(this).val("一缕清风").css("backgroundColor", "red").css("width", "300px")
  })
</script>

断链

对象调用方法之后,返回的已经不是当前的这个对象了,此时再调用方法,就出现了断链 .end() 是修复断链,恢复断链之前的状态

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

<script src="https://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
<script>
  $("ul>li")
    .mouseenter(function () { //鼠标进入事件
      $(this).css("backgroundColor", "red").siblings("li").css("backgroundColor", "");
    })
    .mouseleave(function () { //鼠标离开事件
      $(this).parent().find("li").css("backgroundColor", "");
    })
    .click(function () { //点击事件
      $(this).prevAll("li").css("backgroundColor", "yellow").end().nextAll("li").css("backgroundColor", "blue")
    })
</script>

链式编原理

<script src="https://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
<script>
  function Person(age) {
    this.age = age;
    this.sayHi = function (txt) {
      console.log(txt ? "您好啊:" + txt : "您好啊");
      return this;
    }

    this.eat = function () {
      console.log("中午就吃了一个馒头和咸菜");
      return this;
    };
  }

  var person = new Person(10);
  person.sayHi("一缕清风").eat().sayHi().eat().eat().sayHi()
</script>