前言:
此刻各位老铁们对“jquery链式原理”都比较珍视,看官们都想要分析一些“jquery链式原理”的相关知识。那么小编同时在网上网罗了一些对于“jquery链式原理””的相关资讯,希望小伙伴们能喜欢,同学们快快来学习一下吧!在使用jQuery时候,我们经常会看到或者使用到方法链,例如:
$("#p1").css("color","red").slideUp(2000).slideDown(2000);
这段代码的意思是选择器选择id为p1的html标签,颜色变红,之后slideup,再slidedown。
自然是可以将这几个方法分开写,但是不分开的话不仅有很好的易读性,代码量也会有减少,那么何乐而不为?这种调用函数的方式在jQuery中称为“Chaining”,原理也很简单:能够chaining的方法调用后返回对象本身即可。
下面用java代码做个演示:
Person.java
public class Persion { private int id; private String name; private String phoneNumber; private String address; public Persion() { } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public void setAddress(String address) { this.address = address; } public void printId() { System.out.println(this.id); } public void printName() { System.out.println(this.name); } public void printPhoneNumber() { System.out.println(this.phoneNumber); } public void printAddress() { System.out.println(this.address); }}
Test.java
public class Test { public static void main(String[] args) { Persion persion1 = new Persion(); persion1.setId(3); persion1.setName("John"); persion1.setPhoneNumber("1111111"); persion1.setAddress("US"); persion1.printId(); persion1.printName(); persion1.printPhoneNumber(); persion1.printAddress(); }}
使用chaining:
Person.java
public class Persion { private int id; private String name; private String phoneNumber; private String address; public Persion() { } public Persion setId(int id) { this.id = id; return this; } public Persion setName(String name) { this.name = name; return this; } public Persion setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; return this; } public Persion setAddress(String address) { this.address = address; return this; } public Persion printId() { System.out.println(this.id); return this; } public Persion printName() { System.out.println(this.name); return this; } public Persion printPhoneNumber() { System.out.println(this.phoneNumber); return this; } public Persion printAddress() { System.out.println(this.address); return this; }}
Test.java:
public class Test {
public static void main(String[] args) {
Persion persion1 = new Persion();
persion1.setId(3).setName("John")
.setPhoneNumber("1111111").setAddress("US");
persion1.printId()
.printName()
.printPhoneNumber()
.printAddress();
}
}
链式方法,就是在除最后一个方法外,每个方法都返回一个对象或者调用同一个对象的多个方法。这种编程方式:编程性强;可读性强;代码简洁。但是不易于调试。
标签: #jquery链式原理 #jquery链式