$(“.element”).fadeOut()。delay(500)。fadeIn();
为什么我可以在单个jQuery对象上运行多个函数,何时可以使用此功能? 是否有关于这方面的教程/文档?
$(“.element”).fadeOut()。delay(500)。fadeIn();
为什么我可以在单个jQuery对象上运行多个函数,何时可以使用此功能? 是否有关于这方面的教程/文档?
这被称为方法链,可以帮助您创建流畅界面。每个函数都返回当前 jQuery 实例的引用,这就是为什么可以将调用链接在一起。
首先使用 $('.element')
创建一个 jQuery 实例,它会返回 jQuery 对象的一个实例;这本质上就像一个构造器。然后,jQuery
对象的每个成员函数都会返回对this
的引用,它基本上就是该函数所属实例。因此,不必这样做:
var jQueryObj = $(".element");
jQueryObj.fadeOut();
jQueryObj.delay(500);
jQueryObj.fadeIn();
你可以在一行代码中完成所有操作,因为每个函数的大致形式都类似于这个(这是一个非常简单的例子):
function fadeOut() {
//jQuery code
//...
return this;
}
需要注意的是,并非所有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);
}
现在您可以像这样创建一个实例:
var starship = new Starship()
.name("USS Enterprise")
.registry("NCC-1701-E")
.shipClass("Sovereign");
然后您也可以调用 starship.print()
,但请注意它不返回 this
,这意味着您不能在其后面链接任何内容。
jQuery 的文档将介绍哪些方法是可链接的,哪些不是。如果文档表示该函数返回 jQuery
,则它是可链接的;否则它就不可链接。还要注意,某些方法的可链接性取决于传递的参数。例如,.attr
函数允许您设置属性,只有通过 .attr(attrName, attrValue)
设置属性时才能链接。当仅提供一个参数 (.attr(attrName)
) 时,它将返回属性的值,因此不可链接。
这是通过一种称为 "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);
.html()
、.text()
、parent
、next
、prev
和exit
... - PitaJ