jQuery chaining()
jQuery是一个非常强大的JavaScript框架。通过jQuery,我们可以使用做链,这意味着在一个单一的语句中对一个元素的多个方法进行连锁。
我们一直在使用单一的语句,但现在使用链式方法,我们可以绑定多个方法,使代码简短。这样,浏览器就不必多次查找相同的元素了。
优势:
在jQuery中使用方法链时,它可以确保没有必要多次使用同一个选择器。过度使用选择器会严重拖慢你的代码,因为每次你调用一个选择器,你都会迫使浏览器去寻找它。通过组合或 “连锁 “多个方法,你可以大大减少你让浏览器寻找相同元素的次数,而不必设置任何变量。
使用JavaScript和jQuery实现链式(),以便更好地理解:
代码#1:使用上滑和下滑的方法功能进行连锁。
<!DOCTYPE html>
<html>
<head>
<script src="
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<p id="para">Chaining method in jQuery</p>
<button>Click me</button>
<script type="text/javascript">
(document).ready(function() {
("button").click(function() {
//assigning the color blue
$("#para").css("color", "blue")
//using slide up method
.slideUp(2000)
//using slide down method
.slideDown(2000).
slideUp(2000).
slideDown(4000);
});
});
</script>
</body>
</html>
输出:
代码#2:在jQuery中使用animate函数来实现连锁效果–。
<!DOCTYPE html>
<html>
<head>
<script src="
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<p id="para">Chaining method in jQuery</p>
<button>Click me</button>
<script type="text/javascript">
(document).ready(function() {
("button").click(function() {
$("#para").css("color", "blue").animate({
width: "100%"
})
//it adds animation to the program by styling it
.animate({
fontSize: "46px"
})
.animate({
borderWidth: 30
});
});
});
</script>
</body>
</html>
输出: