Dom*_*fin 14 javascript jquery function
例如: $(".element").fadeOut().delay(500).fadeIn();
为什么我可以在单个jQuery对象上运行多个函数?何时可以使用此功能?有关于此的任何教程/文档吗?
Viv*_*ath 25
这称为链接,可帮助您创建流畅的界面.每个函数都返回对当前jQuery实例的引用,这就是您可以将调用链接在一起的原因.
首先使用$('.element'),创建一个jQuery实例,它返回jQuery对象的一个insance; 它基本上就像一个构造函数.然后jQuery对象的每个成员函数返回一个引用this,这基本上是该函数的拥有实例.所以不要这样做:
var jQueryObj = $(".element");
jQueryObj.fadeOut();
jQueryObj.delay(500);
jQueryObj.fadeIn();
Run Code Online (Sandbox Code Playgroud)
你可以在一行中完成所有这些,因为每个函数或多或少都是这样的(这是一个非常简单的例子):
function fadeOut() {
//jQuery code
//...
return this;
}
Run Code Online (Sandbox Code Playgroud)
值得注意的是,并非所有 jQuery函数都是可链接的; 有些人不会返回对jQuery实例的引用,因此您无法链接它们.实例包括.html(),.text(),和.val().它们返回您想要的实际内容(例如,HTML,文本或输入元素的值).在这些情况下链接是没有意义的.
这是一个非常简单的示例,向您展示链接的工作原理:
var Starship = function() {
this.name = "USS Enterprise";
this.registry = "NCC-1701";
this.shipClass = "Constitution";
};
Starship.prototype.name = function(name) {
this.name = name;
return this;
};
Starship.prototype.registry = function(registry) {
this.registry = registry;
return this;
}
Starship.prototype.shipClass = function(shipClass) {
this.shipClass = shipClass;
return this;
}
Starship.prototype.print = function() {
console.log(this.name + " " + this. registry + " " + this.shipClass);
}
Run Code Online (Sandbox Code Playgroud)
现在你可以像这样创建一个实例:
var starship = new Starship()
.name("USS Enterprise")
.registry("NCC-1701-E")
.shipClass("Sovereign");
Run Code Online (Sandbox Code Playgroud)
然后你也可以打电话starship.print(),但注意它没有返回this,这意味着你不能在那之后链接任何东西.
jQuery的文档将讨论哪些方法是可链接的,哪些方法不可链接.如果文档说该函数返回jQuery,那么它是可链接的; 否则不是.另请注意,某些方法是可链接的,具体取决于传递的参数.例如,.attr允许您设置属性的函数只有在设置属性时才可链接.attr(attrName, attrValue).当只提供一个参数(.attr(attrName))时,它返回属性的值,因此不可链接.
在浏览器中加载jQuery站点,然后单击API Documentation.每个函数都有一个包含return语句的表.如果这样说:

...你可以使用链接.
否则,你不能,例如:

在某些方法中,返回类型取决于传递的参数:


这是使用称为" Fluent Interface " 的设计模式完成的.它也被称为"链接".
例如:
var Car = function() {
var speed, color, doors;
this.setSpeed = function(speed) {
this.speed = speed;
**//Returns the reference to the calling `car` object**
return this;
};
this.setColor = function(color) {
this.color = color;
**//Returns the reference to the calling `car` object**
return this;
};
this.setDoors = function(doors) {
this.doors = doors;
**//Returns the reference to the calling `car` object**
return this;
};
};
// Fluent interface
**//Each method returns a reference to the object itself**
**//so the next method chain is refering back to the previous returned value**
**//ie - itself, the orginal object that started the call chain**
myCar = new Car();
myCar.setSpeed(100).setColor('blue').setDoors(5);
// Example without fluent interface
**// normal, non fluent style, where each method returns Void**
**// so you need to start with the object reference yourself each time**
myCar2 = new Car();
myCar2.setSpeed(100);
myCar2.setColor('blue');
myCar2.setDoors(5);
Run Code Online (Sandbox Code Playgroud)