多行代码合并成一行代码,前提要认清此行代码返回 的是不是对象。是对象才能进行链式编程
--
链式编程的原理:封装方法的时候在最后加上return this
--
遇到断链问题怎么解决呢?使用end()方法
官方文档概述:回到最近的一个"破坏性"操作之前。即,将匹配的元素列表变为前一次的状态。
<ul>
<li>青岛啤酒(TsingTao)</li>
<li>瓦伦丁(Wurenbacher)</li>
<li>雪花(SNOW)</li>
<li>奥丁格教士(Franziskaner)</li>
</ul>
<script type="text/javascript" src="js/jquery-1.12.2.min.js"></script>
<script type="text/javascript">
需求:鼠标移入相应的li,背景颜色高亮,点击后该li的前面所有的li呈现绿色;和后面所有的li呈现蓝色
// 页面加载事件
$(function () {
// 鼠标移入事件
$('ul li').mouseover(function () {
// 让当前的的li显示高亮
$(this).css('backgroundColor', 'yellow').siblings('li').css('backgroundColor', '');
}).click(function () {
// 点击事件
// -----------------一般做法-----------------
// $(this).nextAll().css('backgroundColor', 'blue');
// $(this).prevAll().css('backgroundColor', 'green');
// ---------------------链式编程(解决断链)-----------------
使用.end()解决断链问题(nextAll()返回的不是当前元素而是当前元素前面的所有元素,所有这里造成了断链)
$(this).nextAll().css('backgroundColor', 'blue').end().prevAll().css('backgroundColor', 'green');
}).mouseout(function () {
// 移出事件
$(this).css('backgroundColor', '').siblings().css('backgroundColor', '');
});
});
</script>
网友评论