在jQuery中,如果一直对同一个元素进行函数操作,那么可以使用 函数操作名,一直写下去。
//这是普通的事件绑定$("button").click(function() {console.log("1")})$("button").mouseenter(function() {console.log("2")})$("button").mouseleave(function() {console.log("3")})//与上文功能相同的链式编程$("button").click(function() {console.log("1")}).mouseenter(function() {console.log("2")}).mouseleave(function() {console.log("3")})
实现链式编程的核心,是函数调用结束之后返回的this对象,指的是当前调用者。这里的$("button").click(function(){})调用结束之后,返回this对象,它相当于$("button"),这样和后面的合在一起就实现了$("button").mouseenter(function() {})的函数调用,以上就是链式编程实现的一般步骤。
使用jQuery链式编程,比使用原生js更简单。