Chain operation principle: every time a function is called, the object of the calling function is returned
var $box = $(".box");
var boxReturn = $box.css("width", "200px");
console.log(boxReturn == $box); // true
var boxReturn2 = boxReturn.animate({
height: 200
});
console.log(boxReturn2 == $box); // true
As a result, it can be used to implement chain operations:
var obj = {
name: "李白",
sayName: function (){
console.log("调用了obj的sayName方法");
return this;
},
run: function (){
console.log("调用了obj的run方法");
return this;
},
say: function (){
console.log("调用了obj的say方法");
return this;
},
sing: function (){
console.log("调用了obj的sing方法");
return this;
}
}
obj
.sayName()
.run()
.sing()
.say()
.sayName()
.run()
.sing()
.say();
The jq object will be transferred in the chain operation, you can use end() to change back to the object before the transfer
var innerReturn = boxReturn2.children().css({
height: 100
});
// 调用end()方法返回上一次转移前的对象
innerReturn.end().css({
width: 200,
backgroundColor: "blue"
})
console.log(innerReturn);
Implicit iteration:
Any operation on jq will traverse the obtained jq array and add operations to each item.
The following is a combination of chain operation and implicit iteration:
$("li").css("color", "#fff");
self$("li").css("line-height", "60px");
self$("li").css("background-color", "red").addClass("d1");
function self$(select){
var arr = document.querySelectorAll(select);
arr.css = function (styleName, styleValue){
for(var i= 0; i < arr.length; i ++){
arr[i].style[styleName] = styleValue;
}
return arr;
}
arr.addClass = function (className){
for(var i = 0; i < arr.length; i ++){
arr[i].classList.add(className);
}
return arr;
}
return arr;
}