jQuery笔记
馨er BOSS

jQuery学习笔记

1 概述

1.1 JavaScript库

JavaScript库:即library,是一个封装好的特定的集合(方法和函数)。从封装一大堆函数的角度理解库,就是在这个库中,封装了很多预先定义好的函数在里面,比如动画animate、hide、show,比如获取元素等。
简单理解: 就是一个JS 文件,里面对我们原生js代码进行了封装,存放到里面。这样我们可以快速高效的使用这些封装好的功能了。
比如 jQuery,就是为了快速方便的操作DOM,里面基本都是函数(方法)
常见的JavaScript库

  • jQuery
  • Prototype
  • YUI
  • Dojo
  • Ext JS
  • 移动端的zepto

这些库都是对原生 JavaScript 的封装,内部都是用 JavaScript 实现的

1.2 jQuery 的概念

jQuery 是一个快速、简洁的 JavaScript 库,其设计宗旨是“write Less,Do More”,即倡导写更少的代码,做更多的事情。

j — JavaScript;Query — 查询;意思就是查询js,把js中的DOM操作做了封装,可以快速的查询使用里面的功能

  • jQuery 封装了JavaScript常用的功能代码,优化了 DOM 操作、事件处理、动画设计和Ajax交互

  • 学习jQuery本质: 就是学习调用这些函数(方法)

  • jQuery 出现的目的是加快前端人员的开发速度,我们可以非常方便的调用和使用它,从而提高开发效率

优点

  • 轻量级,核心文件才几十kb,不会影响页面加载速度

  • 跨浏览器兼容,基本兼容了现在主流的浏览器

  • 链式编程、隐式迭代

  • 对事件、样式、动画支持,大大简化了DOM操作

  • 支持插件扩展开发。有着丰富的第三方的插件,例如:树形菜单、日期控件、轮播图等

  • 免费、开源

2 jQuery 的基本使用

官网地址 https://jquery.com/

2.1 版本

各个版本的下载 https://code.jquery.com/

  • 1x :兼容 IE 678 等低版本浏览器, 官网不再更新

  • 2x :不兼容 IE 678 等低版本浏览器, 官网不再更新

  • 3x :不兼容 IE 678 等低版本浏览器, 是官方主要更新维护的版本

2.2 jQuery 的入口函数

1、等着 DOM 结构渲染完毕即可执行内部代码,不必等到所有外部资源加载完成,jQuery 帮我们完成了封装

2、相当于原生 js中的 DOMContentLoaded

3、不同于原生 js中的 load 事件是等页面文档、外部的 js 文件、css文件、图片加载完毕才执行内部代码

4、更推荐使用第一种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
}
</style>

<script>
// 1.等着页面DOM加载完毕再去执行js 代码
// $(document).ready(function() {
// $('div').hide();
// })

// 2.等着页面DOM加载完毕再去执行js 代码 (推荐)
$(function() {
$('div').hide();
});
</script>

<div></div>

2.3 jQuery 的顶级对象 $

  • ,但一般为了方便,通常都直接使用 $

  • 包装成 jQuery对象,就可以调用 jQuery 的方法

2.4 jQuery 对象和 DOM 对象

  • 用原生 JS 获取来的对象就是 DOM 对象

  • jQuery 方法获取的元素就是 jQuery 对象

  • jQuery 对象本质是:利用 $ 对 DOM 对象包装后产生的对象(伪数组形式存储)

注意:只有 jQuery 对象才能使用 jQuery 方法,DOM对象则使用原生的 JavaScirpt 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<style>
div {width: 100px;height: 100px;background-color: pink;}
</style>

<div></div>
<span></span>

<script>
// 1. DOM 对象: 用原生js获取过来的对象就是DOM对象
var myDiv = document.querySelector('div'); // myDiv 是DOM对象
var mySpan = document.querySelector('span'); // mySpan 是DOM对象
console.dir(myDiv);

// 2. jQuery对象: 用jquery方式获取过来的对象是jQuery对象。 本质:通过$把DOM元素进行了包装
$('div'); // $('div')是一个jQuery 对象
$('span'); // $('span')是一个jQuery 对象
console.dir($('div'));

// 3. jQuery 对象只能使用 jQuery 方法,DOM 对象则使用原生的 JavaScirpt 属性和方法
// myDiv.style.display = 'none';
// myDiv.hide(); myDiv是一个dom对象不能使用 jquery里面的hide方法
// $('div').style.display = 'none'; 这个$('div')是一个jQuery对象不能使用原生js 的属性和方法
</script>

DOM 对象与 jQuery 对象之间可以相互转换

  • 因为原生 js 比 jQuery 更大,原生的一些属性和方法 jQuery 没有封装。要想使用这些属性和方法需要把 jQuery 对象转换为 DOM 对象才行

1、DOM 对象转换为 jQuery 对象$(DOM对象)
2、jQuery 对象转换为 DOM 对象(两种方式)
$('div')[index] index 是索引号
$('div').get(index) index 是索引号

3 jQuery 选择器

3.1 jQuery 基础选择器

原生 JS 获取元素方式很多,很杂,而且兼容性情况不一致,因此 jQuery 做了封装,使获取元素统一标准

$("选择器") 里面选择器直接写 CSS 选择器即可,但是要加引号

image.png

3.2 jQuery 层级选择器

image.png

隐式迭代(重要)

遍历内部 DOM 元素(伪数组形式存储)的过程就叫做隐式迭代

简单理解:给匹配到的所有元素进行循环遍历,执行相应的方法,而不用我们再进行循环,简化操作,方便调用

1
2
3
4
5
6
7
8
9
<ul>
<li>相同的操作</li>
<li>相同的操作</li>
<li>相同的操作</li>
</ul>
<script>
// 隐式迭代就是把匹配的所有元素内部进行遍历循环,给每一个元素添加css这个方法
$("ul li").css("color", "red");
</script>

3.3 jQuery 筛选选择器

image.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<ul>
<li>多个里面筛选几个</li>
<li>多个里面筛选几个</li>
<li>多个里面筛选几个</li>
<li>多个里面筛选几个</li>
<li>多个里面筛选几个</li>
</ul>
<ol>
<li>多个里面筛选几个</li>
<li>多个里面筛选几个</li>
<li>多个里面筛选几个</li>
<li>多个里面筛选几个</li>
<li>多个里面筛选几个</li>
</ol>

<script>
$(function() {
$("ul li:first").css("color", "red");
$("ul li:eq(2)").css("color", "blue");
$("ol li:odd").css("color", "skyblue");
$("ol li:even").css("color", "pink");
})
</script>

3.4 jQuery 筛选方法(重点)

image.png

parents()获取所有祖先元素

parents("指定元素")获取指定祖先元素

$(this).index()获取当前元素索引号

重点记住parent() children() find() siblings() eq() hasClass()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div class="nav">
<p>我是cess</p>
<div>
<p>我是ssec</p>
</div>
</div>

<script>
// 注意一下都是方法 带括号
$(function() {
// 1. 父 parent() 返回的是 最近一级的父级元素 亲爸爸
console.log($(".son").parent());

// 2. 子
// (1) 亲儿子 children() 类似子代选择器 ul>li
$(".nav").children("p").css("color", "yellowgreen");
// (2) 可以选里面所有的孩子 包括儿子和孙子 find() 类似于后代选择器
// $(".nav").find("p").css("color", "red");
});
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<ol>
<li>我是ol 的li</li>
<li>我是ol 的li</li>
<li class="item">我是ol 的li</li>
<li>我是ol 的li</li>
<li>我是ol 的li</li>
</ol>
<ul>
<li>我是ol 的li</li>
<li>我是ol 的li</li>
<li>我是ol 的li</li>
</ul>
<div class="current">俺有current</div>
<div>俺木有current</div>


<script>
// 注意一下都是方法 带括号
$(function() {
// 1. 兄弟元素siblings 除了自身元素之外的所有亲兄弟
$("ol .item").siblings("li").css("color", "red");

// 2. 第n个元素
var index = 2;
// (1) 我们可以利用选择器的方式选择
// $("ul li:eq(2)").css("color", "blue");
// $("ul li:eq("+index+")").css("color", "blue");
// (2) 我们可以利用选择方法的方式选择 更推荐这种写法
// $("ul li").eq(index).css("color", "blue");
// $("ul li").eq(2).css("color", "blue");

// 3. 判断是否有某个类名
console.log($("div:first").hasClass("current"));
console.log($("div:last").hasClass("current"));
});
</script>

新浪下拉菜单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<style>
* {margin: 0;padding: 0;}
li {list-style-type: none;}
a {text-decoration: none;font-size: 14px;}
.nav {margin: 100px;}
.nav>li {position: relative;float: left;width: 80px;height: 41px;text-align: center;}
.nav li a {display: block;width: 100%;height: 100%;line-height: 41px;color: #333;}
.nav>li>a:hover {background-color: #eee;}
.nav ul {display: none;position: absolute;top: 41px;left: 0;width: 100%;
border-left: 1px solid #FECC5B;border-right: 1px solid #FECC5B;}
.nav ul li {border-bottom: 1px solid #FECC5B;}
.nav ul li a:hover {background-color: #FFF5DA;}
</style>

<ul class="nav">
<li>
<a href="#">微博</a>
<ul>
<li>
<a href="">私信</a>
</li>
<li>
<a href="">评论</a>
</li>
<li>
<a href="">@我</a>
</li>
</ul>
</li>
<li>
<a href="#">微博</a>
<ul>
<li>
<a href="">私信</a>
</li>
<li>
<a href="">评论</a>
</li>
<li>
<a href="">@我</a>
</li>
</ul>
</li>
</ul>

<script>
$(function() {
// 鼠标经过
$(".nav>li").mouseover(function() {
// $(this) jQuery 当前元素 this不要加引号,隐式迭代
$(this).children("ul").show();
});
// 鼠标离开
$(".nav>li").mouseout(function() {
$(this).children("ul").hide();
})
});
</script>

3.5 jQuery 里面的排他思想

想要多选一的效果,排他思想:当前元素设置样式,其余的兄弟元素清除样式。

1
2
$(this).css("color", "red");
$(this).siblings().css("color", "");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<button>快速</button>
<button>快速</button>
<button>快速</button>

<script>
$(function() {
// 1. 隐式迭代 给所有的按钮都绑定了点击事件
$("button").click(function() {
// 2. 当前的元素变化背景颜色
$(this).css("background", "pink");
// 3. 其余的兄弟去掉背景颜色 隐式迭代
$(this).siblings("button").css("background", "");
});
})
</script>

3.6 链式编程

链式操作是通过对象上的方法最后加上return this把对象再返回回来,对象就可以继续调用方法

  • 链式编程是为了节省代码量,看起来更优雅
  • 使用链式编程一定注意是哪个对象执行样式
1
$(this).css('color', 'red').sibling().css('color', '');     

4 jQuery 样式操作

4.1 操作 css方法

jQuery 可以使用 css 方法来修改简单元素样式,也可以操作类,修改多个样式

1、参数只写属性名,则返回属性值

2、参数为(属性名,属性值),是设置一组样式,属性必须加引号,值如果是数字可以不用跟单位和引号

3、参数可以是对象形式,方便设置多组样式,大括号包含,类似JSON格式,属性可以不用加引号

1
2
3
$(this).css("color");
$(this).css("color", "red");
$(this).css({ "color":"white", "font-size":"20px"});

4.2 设置类样式方法

作用等同于以前的classList,可以操作类样式, 注意操作类里面的参数不要加点

1、添加类

2、移除类

3、切换类

1
2
3
$("div").addClass("current");
$("div").removeClass("current");
$("div").toggleClass("current");

4.3 类操作与 className 区别

  • 原生 JS 中 className 会覆盖元素原先里面的类
  • jQuery 里面类操作只是对指定类进行操作,不影响原先的类名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<script src="jquery.min.js"></script>
<style>
* {margin: 0;padding: 0;}
li {list-style-type: none;}
.tab {width: 978px;margin: 100px auto;}
.tab_list {height: 39px;border: 1px solid #ccc;background-color: #f1f1f1;}
.tab_list li {float: left;height: 39px;line-height: 39px;padding: 0 20px;
text-align: center;cursor: pointer;}
.tab_list .current {background-color: #c81623;color: #fff;}
.item_info {padding: 20px 0 0 20px;}
.item {display: none;}
</style>

<body>
<div class="tab">
<div class="tab_list">
<ul>
<li class="current">商品介绍</li>
<li>规格与包装</li>
<li>售后保障</li>
<li>商品评价(50000)</li>
<li>手机社区</li>
</ul>
</div>
<div class="tab_con">
<div class="item" style="display: block;">
商品介绍模块内容
</div>
<div class="item">
规格与包装模块内容
</div>
<div class="item">
售后保障模块内容
</div>
<div class="item">
商品评价(50000)模块内容
</div>
<div class="item">
手机社区模块内容
</div>

</div>
</div>

<script>
$(function() {
// 1.点击上部的li,当前li 添加current类,其余兄弟移除类
$(".tab_list li").click(function() {
// 链式编程操作
$(this).addClass("current").siblings().removeClass("current");
// 2.点击的同时,得到当前li 的索引号
var index = $(this).index();
console.log(index);
// 3.让下部里面相应索引号的item显示,其余的item隐藏
$(".tab_con .item").eq(index).show().siblings().hide();
});
})
</script>

5 jQuery 效果

jQuery 给我们封装了很多动画效果,最为常见的如下

image.png

5.1 显示隐藏效果

显示 show([speed,[easing],[fn]])

隐藏 hide([speed,[easing],[fn]])

切换 toggle([speed,[easing],[fn]])

1、参数都可以省略, 无动画直接显示

2、speed 三种预定速度之一的字符串(’slow’, ‘normal’, ‘fast’)或表示动画时长的毫秒数值(如:1000)

3、easing (Optional) 用来指定切换效果,默认是“swing”,可用参数“linear”

4、fn 回调函数,在动画完成时执行的函数,每个元素执行一次

建议:平时一般不带参数,直接显示隐藏即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<script src="jquery.min.js"></script>
<style>
div {width: 150px;height: 300px;background-color: pink;}
</style>

<button>显示</button>
<button>隐藏</button>
<button>切换</button>
<div></div>

<script>
$(function() {
$("button").eq(0).click(function() {
$("div").show(1000, function() {
alert(1);
});
})
$("button").eq(1).click(function() {
$("div").hide(1000, function() {
alert(1);
});
})
$("button").eq(2).click(function() {
$("div").toggle(1000);
})
});
</script>

5.2 滑动效果

下滑效果 slideDown([speed,[easing],[fn]])

上滑效果 slideUp([speed,[easing],[fn]])

滑动切换 slideToggle([speed,[easing],[fn]])

1、参数都可以省略, 无动画直接显示
2、speed 三种预定速度之一的字符串(’slow’, ‘normal’, ‘fast’)或表示动画时长的毫秒数值(如:1000)
3、easing (Optional) 用来指定切换效果,默认是“swing”(慢快慢),可用参数“linear”(匀速)
4、fn 回调函数,在动画完成时执行的函数,每个元素执行一次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script src="jquery.min.js"></script>
<style>
div {width: 150px;height: 300px;background-color: pink;display: none;}
</style>

<button>下拉滑动</button>
<button>上拉滑动</button>
<button>切换滑动</button>
<div></div>

<script>
$(function() {
$("button").eq(0).click(function() {
$("div").slideDown(); // 下滑动 slideDown()
})
$("button").eq(1).click(function() {
$("div").slideUp(500); // 上滑动 slideUp()
})
$("button").eq(2).click(function() {
$("div").slideToggle(500); // 滑动切换 slideToggle()
});
});
</script>

5.3 鼠标移进移出

hover([over,] out)

  • over 鼠标移到元素上要触发的函数(相当于mouseenter)
  • out 鼠标移出元素要触发的函数(相当于mouseleave)
  • 如果只写一个函数,则鼠标经过和离开都会触发它

新浪下拉菜单改进

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 鼠标经过
$(".nav>li").mouseover(function() {
$(this).children("ul").slideDown(200);
});
// 鼠标离开
$(".nav>li").mouseout(function() {
$(this).children("ul").slideUp(200);
});


// 1. 事件切换 hover 就是鼠标经过和离开的复合写法
$(".nav>li").hover(function() {
$(this).children("ul").slideDown(200);
}, function() {
$(this).children("ul").slideUp(200);
});


// 2. 事件切换 hover 如果只写一个函数,那么鼠标经过和鼠标离开都会触发这个函数
$(".nav>li").hover(function() {
$(this).children("ul").slideToggle();
});

5.5 动画队列及停止排队方法

1、动画或效果队列
动画或者效果一旦触发就会执行,如果多次触发,就造成多个动画或者效果排队执行。
2、停止排队stop()
注意: stop() 写到动画或者效果的前面, 相当于停止结束上一次的动画

新浪下拉菜单改进2

1
2
3
4
$(".nav>li").hover(function() {
// stop 方法必须写到动画的前面
$(this).children("ul").stop().slideToggle();
});

5.6 淡入淡出效果

淡入效果 fadeIn([speed, [easing], [fn]])

淡出效果 fadeOut([speed, [easing], [fn]])

淡入淡出 fadeToggle([speed, [easing], [fn]])

渐进方式调整到指定的不透明度 fadeTo(speed, opacity, [easing], [fn]])

  • opacity 透明度必须写,取值 0~1 之间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<style>
div {width: 150px;height: 300px;background-color: pink;display: none;}
</style>
<script src="jquery.min.js"></script>

<button>淡入效果</button>
<button>淡出效果</button>
<button>淡入淡出切换</button>
<button>修改透明度</button>
<div></div>
<script>
$(function() {
$("button").eq(0).click(function() {
// 淡入 fadeIn()
$("div").fadeIn(1000);
})
$("button").eq(1).click(function() {
// 淡出 fadeOut()
$("div").fadeOut(1000);

})
$("button").eq(2).click(function() {
// 淡入淡出切换 fadeToggle()
$("div").fadeToggle(1000);

});
$("button").eq(3).click(function() {
// 修改透明度 fadeTo() 这个速度和透明度要必须写
$("div").fadeTo(1000, 0.5);
});
});

5.7 自定义动画 animate

animate(params, [speed], [easing], [fn])

  • params 想要更改的样式属性,以对象形式传递,必须写。 属性名可以不用带引号, 如果是复合属性则需要采取驼峰命名法 borderLeft。其余参数都可以省略
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<style>
div {
position: absolute;
width: 200px;
height: 200px;
background-color: pink;
}
</style>

<button>动起来</button>
<div></div>
<script>
$(function() {
$("button").click(function() {
$("div").animate({
left: 500,
top: 300,
opacity: .4,
width: 500
}, 500);
})
})
</script>

王者荣耀手风琴效果

手风琴动画.gif

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script type="text/javascript">
$(function() {
// 鼠标经过某个小li 有两步操作:
$(".king li").mouseenter(function() {
// 1.当前小li 宽度变为 224px, 同时里面的小图片淡出,大图片淡入
$(this).stop().animate({
width: 224
}).find(".small").stop().fadeOut().siblings(".big").stop().fadeIn();
// 2.其余兄弟小li宽度变为69px, 小图片淡入, 大图片淡出
$(this).siblings("li").stop().animate({
width: 69
}).find(".small").stop().fadeIn().siblings(".big").stop().fadeOut();
})
});
</script>

6 jQuery 属性操作

6.1 设置或获取元素固有属性值 prop()

所谓元素固有属性就是元素本身自带的属性,比如 元素里面的 href,比如 元素里面的 type

获取属性 prop("属性")

设置属性 prop("属性", "属性值")

6.2 设置或获取元素自定义属性值 attr()

用户自己给元素添加的属性,我们称为自定义属性。 比如给 div 添加 index =”1”

获取属性 attr("属性")

设置属性 attr("属性", "属性值")

6.3 数据缓存 data()

data() 方法可以在指定的元素上存取数据,并不会修改 DOM 元素结构。一旦页面刷新,之前存放的数据都将被移除

获取数据 data("name")

附加数据 data("name', 'value")

同时,还可以读取 HTML5 自定义属性 data-index ,得到的是数字型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<a href="http://www.itcast.cn" title="都挺好">都挺好</a>
<input type="checkbox" name="" id="" checked>
<div index="1" data-index="2">我是div</div>
<span>123</span>

<script>
$(function() {
//1. element.prop("属性名") 获取元素固有的属性值
console.log($("a").prop("href"));
$("a").prop("title", "我们都挺好");
$("input").change(function() {
console.log($(this).prop("checked"));
});

// 2. 元素的自定义属性 我们通过 attr()
// console.log($("div").prop("index")); 拿不到
console.log($("div").attr("index"));
$("div").attr("index", 4);
console.log($("div").attr("data-index"));

// 3. 数据缓存 data() 这个里面的数据是存放在元素的内存里面
$("span").data("uname", "andy");
console.log($("span").data("uname"));
// 这个方法获取data-index,1.h5自定义属性不用写data- 2.返回的是数字型
console.log($("div").data("index"));
})
</script>

7 jQuery 内容文本值

主要针对元素的内容还有表单的值操作

7.1 普通元素内容 html()( 相当于原生inner HTML)

html() 获取元素的内容

html("内容") 设置元素的内容

7.2 普通元素文本内容 text() (相当与原生 innerText)

text() 获取元素的内容

text("内容") 设置元素的内容

7.3 表单的值 val()( 相当于原生value)

val() 获取元素的内容

val("内容") 设置元素的内容

toFixed(n)保留几位小数

8 jQuery 元素操作

8.1 遍历元素

jQuery 隐式迭代是对同一类元素做了同样的操作。 如果想要给同一类元素做不同操作,就需要用到遍历。

1、each(function(index, domEle){}) 方法遍历匹配的每一个元素。主要用DOM处理

2、each 里面的回调函数有2个参数

index 是每个元素的索引号

demEle 是每个DOM元素对象,不是jquery对象

3、所以要想使用jquery方法,需要给这个dom元素转换为jquery对象 $(domEle)

1
$("div").each(function (index, domEle) {xxx;})   

1、$.each(object,function(index, element) {})方法可用于遍历任何对象。主要用于数据处理,比如数组,对象

2、里面的函数有2个参数

index 是每个元素的索引号

element 遍历内容

1
$.each(object, function(index, element) {xxx;})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<div>1</div>
<div>2</div>
<div>3</div>

<script>
$(function() {
// 如果针对于同一类元素做不同操作,需要用到遍历元素(类似for,但是比for强大)
var sum = 0;
// 1. each() 方法遍历元素
var arr = ["red", "green", "blue"];
$("div").each(function(i, domEle) {
// 回调函数第一个参数一定是索引号,可以自己指定索引号号名称
// 回调函数第二个参数一定是 dom元素对象 也是自己命名
$(domEle).css("color", arr[i]);
sum += parseInt($(domEle).text());
})
console.log(sum);

// 2. $.each() 方法遍历元素 主要用于遍历数据,处理数据
// $.each($("div"), function(i, ele) {
// console.log(i);
// console.log(ele);
// });
// $.each(arr, function(i, ele) {
// console.log(i);
// console.log(ele);
// })
$.each({
name: "andy",
age: 18
}, function(i, ele) {
console.log(i); // 输出的是 name age 属性名
console.log(ele); // 输出的是 andy 18 属性值
})
})
</script>

8.2 创建元素

$("<li></li>") 动态的创建了一个

  • 8.3 添加元素

    1、内部添加

    element.append("内容")把内容放入匹配元素内部最后面,类似原生 appendChild

    element.prepend("内容") 把内容放入匹配元素内部最前面

    反过来有appendTo() prependTo()

    2、外部添加

    element.after("内容")把内容放入目标元素后面

    element.brfore("内容") 把内容放入目标元素前面

    8.4 删除元素

    element.remove() 删除匹配的元素(本身)

    element.empty() 删除匹配的元素集合中所有的子节点,等价于 element.html("")

    element.remove("") 清空匹配的元素内容

    • empt() 和 html(‘’’’) 作用等价,都可以删除元素里面的内容,只不过 html 还可以设置内容
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <ul>
    <li>原先的li</li>
    </ul>
    <div class="test">原先的div</div>
    <script>
    $(function() {
    // 1. 创建元素
    var li = $("<li>后来创建的li</li>");

    // 2. 添加元素
    // (1) 内部添加
    // $("ul").append(li); 内部添加并且放到内容的最后面
    $("ul").prepend(li); // 内部添加并且放到内容的最前面
    // (2) 外部添加
    var div = $("<div>我是后妈生的</div>");
    // $(".test").after(div);
    $(".test").before(div);

    // 3. 删除元素
    // $("ul").remove(); 可以删除匹配的元素 自杀
    // $("ul").empty(); // 可以删除匹配的元素里面的子节点 孩子
    $("ul").html(""); // 可以删除匹配的元素里面的子节点 孩子
    })
    </script>

    9 jQuery 尺寸、位置操作

    9.1 jQuery 尺寸

    image.png

    • 以上参数为空,则是获取相应值,返回的是数字型

    • 如果参数为数字,则是修改相应值

    • 参数可以不必写单位

    9.2 jQuery 位置

    offset() 设置或获取元素偏移

    • offset() 方法设置或返回被选元素相对于文档的偏移坐标,跟父级没有关系

    • 返回Object对象包含2个属性 left、top,offset().top 用于获取距离文档顶部的距离,offset().left 用于获取距离文档左侧的距离

    • 可以设置元素的偏移:offset({ top: 10, left: 30 });

    position() 获取元素偏移

    • position() 方法用于返回被选元素相对于带有定位的父级偏移坐标,如果父级都没有定位,则以文档为准

    • 该方法有2个属性 left、top。position().top 用于获取距离定位父级顶部的距离,position().left 用于获取距离定位父级左侧的距离

    • 该方法只能获取,不能设置

    scrollTop() scrollLeft() 设置或获取元素被卷去的头部和左侧

    • scrollTop() 方法设置或返回被选元素被卷去的头部

    • 不跟参数是获取,参数为不带单位的数字则是设置被卷去的头部

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    <style>
    body {height: 2000px;}
    .back {position: fixed;width: 50px;height: 50px;background-color: pink;
    right: 30px;bottom: 100px;display: none;}
    .container {width: 900px;height: 500px;background-color: skyblue;margin: 400px auto;}
    </style>
    <script src="jquery.min.js"></script>

    <div class="back">返回顶部</div>
    <div class="container"></div>

    <script>
    $(function() {
    $(document).scrollTop(100);

    // 页面滚动事件
    var boxTop = $(".container").offset().top;
    $(window).scroll(function() {
    // console.log(11);
    console.log($(document).scrollTop());
    if ($(document).scrollTop() >= boxTop) {
    $(".back").fadeIn();
    } else {
    $(".back").fadeOut();
    }
    });

    // 返回顶部
    $(".back").click(function() {
    // $(document).scrollTop(0);
    $("body, html").stop().animate({
    scrollTop: 0
    });
    // $(document).stop().animate({
    // scrollTop: 0
    // }); 不能是文档而是 html和body元素做动画
    })
    })
    </script>

    10 jQuery 事件

    10.1 jQuery 事件注册

    element.事件(function(){})

    10.2 jQuery 事件处理

    1、on() 绑定事件

    on() 方法在匹配元素上绑定一个或多个事件的事件处理函数

    element.on(events, [selector], fn)

    • events 一个或多个用空格分隔的事件类型,如”click”或”keydown” 。

    • selector 元素的子元素选择器

    • fn 回调函数 即绑定在元素身上的侦听函数

    优势

    • 可以绑定多个事件,多个处理事件处理程序

    • 可以事件委派操作 。事件委派的定义就是,把原来加给子元素身上的事件绑定在父元素身上,就是把事件委派给父元素

    • 动态创建的元素,click() 没有办法绑定事件, on() 可以给动态生成的元素绑定事件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    <style>
    div {width: 100px;height: 100px;background-color: pink;}
    .current {background-color: purple;}
    </style>
    <script src="jquery.min.js"></script>

    <div></div>
    <ul>
    <li>我们都是好孩子</li>
    <li>我们都是好孩子</li>
    <li>我们都是好孩子</li>
    <li>我们都是好孩子</li>
    <li>我们都是好孩子</li>
    </ul>
    <ol>
    </ol>

    <script>
    $(function () {
    // 1. 单个事件注册
    // $("div").click(function() {
    // $(this).css("background", "purple");
    // });
    // $("div").mouseenter(function() {
    // $(this).css("background", "skyblue");
    // });

    // 2. 事件处理on
    // (1) on可以绑定1个或者多个事件处理程序
    $("div").on({
    mouseenter: function() {
    $(this).css("background", "skyblue");
    },
    click: function() {
    $(this).css("background", "purple");
    },
    mouseleave: function() {
    $(this).css("background", "blue");
    }
    });

    // 或者 多个事件中间用空格隔开
    $("div").on("mouseenter mouseleave", function () {
    $(this).toggleClass("current");
    });

    // (2) on可以实现事件委托(委派)
    // click 是绑定在ul 身上的,但是 触发的对象是 ul 里面的小li
    // $("ul li").click();
    $("ul").on("click", "li", function () {
    alert(11);
    });

    // (3) on可以给未来动态创建的元素绑定事件
    // $("ol li").click(function() { 这种不行
    // alert(11);
    // })
    $("ol").on("click", "li", function () {
    alert(11);
    })
    var li = $("<li>我是后来创建的</li>");
    $("ol").append(li);
    })
    </script>

    在此之前有 bind() live() delegate() 等方法来处理事件绑定或者事件委派,最新版本的请用 on 替代

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    <style>
    * {margin: 0;padding: 0}
    ul {list-style: none}
    .box {width: 600px;margin: 100px auto;border: 1px solid #000;padding: 20px;}
    textarea {width: 450px;height: 160px;outline: none;resize: none;}
    ul {width: 450px;padding-left: 80px;}
    ul li {line-height: 25px;border-bottom: 1px dashed #cccccc;display: none;}
    input {float: right;}
    ul li a {float: right;}
    </style>

    <script src="jquery.min.js"></script>
    <script>
    $(function() {
    // 1.点击发布按钮, 动态创建一个小li,放入文本框的内容和删除按钮, 并且添加到ul 中
    $(".btn").click(function () {
    if ($(".txt").val() != "") {
    var li = $("<li></li>");
    li.html($(".txt").val() + "<a>删除</a>");
    $("ul").prepend(li)
    li.stop().slideDown();
    $(".txt").val("");
    }
    });

    // 2.点击的删除按钮,可以删除当前的微博留言li
    // $("ul a").click(function() { // 此时的click不能给动态创建的a添加事件
    // alert(11);
    // })
    // on可以给动态创建的元素绑定事件
    $("ul").on("click", "a", function() {
    $(this).parent().slideUp(function() {
    $(this).remove();
    });
    })
    })
    </script>

    <div class="box" id="weibo">
    <span>微博发布</span>
    <textarea name="" class="txt" cols="30" rows="10"></textarea>
    <button class="btn">发布</button>
    <ul>
    </ul>
    </div>

    2、off() 解绑事件

    off() 方法可以移除通过 on() 方法添加的事件处理程序

    1
    2
    3
    $("p").off()								// 解绑p元素所有事件处理程序
    $("p").off( "click") // 解绑p元素上面的点击事件 后面的 foo 是侦听函数名
    $("ul").off("click", "li"); // 解绑事件委托

    如果有的事件只想触发一次, 可以使用one()来绑定事件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    <style>
    div {width: 100px;height: 100px;background-color: pink;}
    </style>
    <script src="jquery.min.js"></script>
    <script>
    $(function() {
    $("div").on({
    click: function() {
    console.log("我点击了");
    },
    mouseover: function() {
    console.log('我鼠标经过了');
    }
    });
    $("ul").on("click", "li", function() {
    alert(11);
    });

    // 1. 事件解绑 off
    // $("div").off(); // 这个是解除了div身上的所有事件
    $("div").off("click"); // 这个是解除了div身上的点击事件
    $("ul").off("click", "li");

    // 2. one() 但是它只能触发事件一次
    $("p").one("click", function() {
    alert(11);
    })
    })
    </script>

    <div></div>
    <ul>
    <li>我们都是好孩子</li>
    <li>我们都是好孩子</li>
    <li>我们都是好孩子</li>
    </ul>
    <p>hello</p>

    3、自动触发事件 trigger()

    有些事件希望自动触发, 比如轮播图自动播放功能跟点击右侧按钮一致。可以利用定时器自动触发右侧按钮点击事件,不必鼠标点击触发

    triggerHandler模式不会触发元素的默认行为,这是和前面两种的区别

    1
    2
    3
    4
    5
    6
    7
    8
    9
    element.click()  // 第一种简写形式
    element.trigger("事件") // 第二种自动触发模式
    element.triggerHandler(事件) // 第三种自动触发模式

    $("p").on("click", function () {
    alert("hi~");
    });

    $("p").trigger("click"); // 此时自动触发点击事件,不需要鼠标点击

    10.3 jQuery 事件对象

    事件被触发,就会有事件对象的产生

    阻止默认行为event.preventDefault()或者return false

    阻止冒泡event.stopPropagation()

    11 jQuery 其他方法

    11.1 对象拷贝

    如果想要把某个对象拷贝(合并) 给另外一个对象使用,此时可以使用 $.extend() 方法

    $.extend([deep], target, object1, [objectN])

    1、deep 如果设为 true 为深拷贝, 默认为 false 浅拷贝

    2、target 要拷贝到的目标对象

    3、object1 待拷贝到第一个对象的对象

    4、objectN 待拷贝到第N个对象的对象

    深浅拷贝

    • 浅拷贝是把被拷贝的对象复杂数据类型中的地址拷贝给目标对象,修改目标对象会影响被拷贝对象

    • 深拷贝是完全克隆(拷贝的对象,而不是地址),修改目标对象不会影响被拷贝对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    <script>
    $(function() {
    var targetObj = {
    id: 0,
    msg: {
    sex: '男'
    }
    };
    var obj = {
    id: 1,
    name: "andy",
    msg: {
    age: 18
    }
    };
    // $.extend(target, obj);
    $.extend(targetObj, obj);
    console.log(targetObj); // 会覆盖targetObj 里面原来的同名数据

    // // 1. 浅拷贝把原来对象里面的复杂数据类型地址拷贝给目标对象
    targetObj.msg.age = 20;
    console.log(targetObj);
    console.log(obj);

    // 2. 深拷贝把里面的数据完全复制一份给目标对象 如果里面有不冲突的属性,会合并到一起
    $.extend(true, targetObj, obj);
    targetObj.msg.age = 20;
    console.log(targetObj); // msg :{sex: "男", age: 20}
    console.log(obj);
    })
    </script>

    11.2 多库共存

    jQuery使用$作为标识符,随着jQuery的流行,其他js库也会用这$作为标识符, 这样一起使用会引起冲突,需要一个解决方案,让jQuery 和其他的js库不存在冲突,可以同时存在,这就叫做多库共存。

    jQuery 解决方案

    1、把里面的 $ 符号 统一改为 jQuery。 比如 jQuery(''div'')

    2、jQuery 变量规定新的名称$.noConflict() var xx = $.noConflict();

    11.3 插件

    jQuery 功能比较有限,想要更复杂的特效效果,可以借助于 jQuery 插件完成

    注意:这些插件也是依赖于jQuery来完成的,所以必须要先引入jQuery文件,因此也称为 jQuery 插件

    1、jQuery 插件常用的网站

    jQuery 插件库 http://www.jq22.com/ 懒加载

    jQuery 之家 http://www.htmleaf.com/

    2、jQuery 插件使用步骤

    引入相关文件(jQuery 文件 和 插件文件)

    复制相关html、css、js (调用插件)

    3、jQuery 插件演示

    1、瀑布流

    2、图片懒加载(图片使用延迟加载在可提高网页下载速度。它也能帮助减轻服务器负载)

    当我们页面滑动到可视区域,再显示图片。

    我们使用jquery插件库 EasyLazyload。 注意,此时的js引入文件和js调用必须写到 DOM元素(图片)最后面

    EasyLazyload.js(3 KB)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    /**
    * Created by channng on 16/12/5.
    */
    ;(function($){

    var defaults = {
    coverColor:"#dfdfdf",
    coverDiv:"",
    showTime:300,
    offsetBottom:0,
    offsetTopm:50,
    onLoadBackEnd:function(index,dom){},
    onLoadBackStart:function(index,dom){}
    }

    //所有待load src
    var srcList = []

    var lazyLoadCoutn = 0;
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    var lazyImgList = $("img[data-lazy-src]");
    var default_base64_src ="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";

    //获取img
    function getImgNaturalDimensions(src, callback,lazyLoadCoutn) {
    var nWidth, nHeight

    var image = new Image()
    image.src = src;
    image.onload = function() {
    callback(image.width, image.height);
    defaults.onLoadBackStart(lazyLoadCoutn,$("img[data-lazy-src]:eq("+lazyLoadCoutn+")"));
    }
    return [nWidth, nHeight];
    }

    function showImg(lazyLoadCoutn,callback){

    var src = lazyImgList.eq(lazyLoadCoutn).attr("data-lazy-src")
    getImgNaturalDimensions(src, function () {
    try {

    meng($("img[data-lazy-src]:eq("+lazyLoadCoutn+")") ,lazyLoadCoutn,callback)
    }catch(error) {

    }
    },lazyLoadCoutn)
    }

    function meng(jDom,lazyLoadCoutn,callback){
    if(jDom.attr("data-comp")){
    return;
    }
    jDom.css("visibility","hidden");
    jDom.attr("src",jDom.attr("data-lazy-src"))
    var w = jDom.width();
    var h = jDom.height();
    var offsetTop = jDom.offset().top;
    var offsetLeft = jDom.offset().left;

    jDom.css("visibility","visible");
    $("body").append("<div class='meng-lazy-div"+lazyLoadCoutn+"' style='background-color: "+defaults.coverColor+";position:absolute;width:"+w+"px;height:"+h+"px;top:"+offsetTop+"px;left:"+offsetLeft+"px;z-index:500'>"+defaults.coverDiv+"</div>");
    noneM(lazyLoadCoutn,callback,jDom);
    jDom.attr("data-comp","true");
    }

    function noneM(lazyLoadCoutn,callback,jDom){
    if(true){
    $(".meng-lazy-div"+lazyLoadCoutn).animate({opacity:"0"},defaults.showTime,function(){
    $(this).remove();
    defaults.onLoadBackEnd(lazyLoadCoutn,jDom)
    callback();
    });
    }
    }

    function checkOffset(){
    var scrollTop = $(document).scrollTop();
    var onlazyList = [];
    lazyImgList.each(function(index){
    var dom = $(this);
    if(!dom.attr("data-comp")){
    if(dom.offset().top-scrollTop+defaults.offsetTopm>=0&&dom.offset().top-scrollTop<(windowHeight+defaults.offsetBottom)){
    onlazyList.push(index);
    }
    }
    })

    if(onlazyList.length!=0){
    showImg(onlazyList[0],function(){
    checkOffset();
    });
    }
    }

    function range(){
    checkOffset();

    }

    function init(setting){
    defaults = $.extend(defaults,setting);

    lazyImgList.each(function(){
    var sr = $(this).attr("data-lazy-src");
    srcList.push(sr);

    $(this).attr("src",default_base64_src);
    });
    range();
    window.onscroll=function(){
    range()
    }
    }

    window.lazyLoadInit = init;


    })($)

    EasyLazyload.min.js(2 KB)

    1
    !function(t){function o(o,a,i){var n,c,e=new Image;return e.src=o,e.onload=function(){a(e.width,e.height),r.onLoadBackStart(i,t("img[data-lazy-src]:eq("+i+")"))},[n,c]}function a(a,n){var c=l.eq(a).attr("data-lazy-src");o(c,function(){try{i(t("img[data-lazy-src]:eq("+a+")"),a,n)}catch(t){}},a)}function i(o,a,i){if(!o.attr("data-comp")){o.css("visibility","hidden"),o.attr("src",o.attr("data-lazy-src"));var c=o.width(),e=o.height(),d=o.offset().top,f=o.offset().left;o.css("visibility","visible"),t("body").append("<div class='meng-lazy-div"+a+"' style='background-color: "+r.coverColor+";position:absolute;width:"+c+"px;height:"+e+"px;top:"+d+"px;left:"+f+"px;z-index:500'>"+r.coverDiv+"</div>"),n(a,i,o),o.attr("data-comp","true")}}function n(o,a,i){t(".meng-lazy-div"+o).animate({opacity:"0"},r.showTime,function(){t(this).remove(),r.onLoadBackEnd(o,i),a()})}function c(){var o=t(document).scrollTop(),i=[];l.each(function(a){var n=t(this);n.attr("data-comp")||n.offset().top-o+r.offsetTopm>=0&&n.offset().top-o<s+r.offsetBottom&&i.push(a)}),0!=i.length&&a(i[0],function(){c()})}function e(){c()}function d(o){r=t.extend(r,o),l.each(function(){var o=t(this).attr("data-lazy-src");f.push(o),t(this).attr("src",A)}),e(),window.onscroll=function(){e()}}var r={coverColor:"#dfdfdf",coverDiv:"",showTime:300,offsetBottom:0,offsetTopm:50,onLoadBackEnd:function(t,o){},onLoadBackStart:function(t,o){}},f=[],s=t(window).height(),l=(t(window).width(),t("img[data-lazy-src]")),A="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";window.lazyLoadInit=d}($);

    3、全屏滚动(fullpage.js)

    gitHub https://github.com/alvarotrigo/fullPage.js

    中文翻译网站 http://www.dowebok.com/demo/2014/77/

    4、bootstrap JS 插件

    bootstrap 框架也是依赖于 jQuery 开发的,因此里面的 js插件使用 ,也必须引入 jQuery 文件

    https://v3.bootcss.com/

    12 todolist案例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    <link rel="stylesheet" href="index.css">
    <script src="jquery.min.js"></script>
    <script src="todolist.js"></script>

    <header>
    <section>
    <label for="title">ToDoList</label>
    <input type="text" id="title" name="title" placeholder="添加ToDo"
    required="required" autocomplete="off" />
    </section>
    </header>
    <section>
    <h2>正在进行 <span id="todocount"></span></h2>
    <ol id="todolist" class="demo-box">

    </ol>
    <h2>已经完成 <span id="donecount"></span></h2>
    <ul id="donelist">

    </ul>
    </section>
    <footer>
    Copyright &copy; 2014 todolist.cn
    </footer>
    </body>

    todolist.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    $(function () {
    // 1. 按下回车 把完整数据 存储到本地存储里面
    // 存储的数据格式 var todolist = [{title: "xxx", done: false}]
    load();

    $("#title").on("keydown", function (event) {
    if (event.keyCode === 13) {
    if ($(this).val() === "") {
    alert("请输入您要的操作");
    } else {
    // 先读取本地存储原来的数据
    var local = getDate();
    // 把local数组进行更新数据 把最新的数据追加给local数组
    local.push({ title: $(this).val(), done: false });
    // 把这个数组local 存储给本地存储
    saveDate(local);
    // 2. toDoList 本地存储数据渲染加载到页面
    load();
    $(this).val("");
    }
    }
    });

    // 3. toDoList 删除操作
    $("ol, ul").on("click", "a", function () {
    // 先获取本地存储
    var data = getDate();
    // 修改数据
    var index = $(this).attr("id");
    data.splice(index, 1);
    saveDate(data);
    load();
    });

    // 4. toDoList 正在进行和已完成选项操作
    $("ol, ul").on("click", "input", function () {
    // 先获取本地存储的数据
    var data = getDate();
    // 修改数据
    var index = $(this).siblings("a").attr("id");
    // data[?].done = ?
    data[index].done = $(this).prop("checked");
    saveDate(data);
    load();
    });

    // 读取本地存储的数据
    function getDate() {
    var data = localStorage.getItem("todolist");
    if (data !== null) {
    // 本地存储里面的数据是字符串格式的 但是我们需要的是对象格式的
    return JSON.parse(data);
    } else {
    return [];
    }
    }

    // 保存本地存储数据
    function saveDate(data) {
    localStorage.setItem("todolist", JSON.stringify(data));
    }

    // 渲染加载数据
    function load() {
    // 读取本地存储的数据
    var data = getDate();
    console.log(data);
    // 遍历之前先要清空ol里面的元素内容
    $("ol, ul").empty();
    var todoCount = 0; // 正在进行的个数
    var doneCount = 0; // 已经完成的个数
    // 遍历这个数据
    $.each(data, function (i, n) {
    // console.log(n);
    if (n.done) {
    $("ul").prepend("<li><input type='checkbox' checked='checked' > <p>"
    + n.title + "</p> <a href='javascript:;' id=" + i + " ></a></li>");
    doneCount++;
    } else {
    $("ol").prepend("<li><input type='checkbox' > <p>"
    + n.title + "</p> <a href='javascript:;' id=" + i + " ></a></li>");
    todoCount++;
    }
    });
    $("#todocount").text(todoCount);
    $("#donecount").text(doneCount);
    }
    })

    index.css

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    body {
    margin: 0;
    padding: 0;
    font-size: 16px;
    background: #CDCDCD;
    }

    header {
    height: 50px;
    background: #333;
    background: rgba(47, 47, 47, 0.98);
    }

    section {
    margin: 0 auto;
    }

    label {
    float: left;
    width: 100px;
    line-height: 50px;
    color: #DDD;
    font-size: 24px;
    cursor: pointer;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    }

    header input {
    float: right;
    width: 60%;
    height: 24px;
    margin-top: 12px;
    text-indent: 10px;
    border-radius: 5px;
    box-shadow: 0 1px 0 rgba(255, 255, 255, 0.24), 0 1px 6px rgba(0, 0, 0, 0.45) inset;
    border: none
    }

    input:focus {
    outline-width: 0
    }

    h2 {
    position: relative;
    }

    span {
    position: absolute;
    top: 2px;
    right: 5px;
    display: inline-block;
    padding: 0 5px;
    height: 20px;
    border-radius: 20px;
    background: #E6E6FA;
    line-height: 22px;
    text-align: center;
    color: #666;
    font-size: 14px;
    }

    ol,
    ul {
    padding: 0;
    list-style: none;
    }

    li input {
    position: absolute;
    top: 2px;
    left: 10px;
    width: 22px;
    height: 22px;
    cursor: pointer;
    }

    p {
    margin: 0;
    }

    li p input {
    top: 3px;
    left: 40px;
    width: 70%;
    height: 20px;
    line-height: 14px;
    text-indent: 5px;
    font-size: 14px;
    }

    li {
    height: 32px;
    line-height: 32px;
    background: #fff;
    position: relative;
    margin-bottom: 10px;
    padding: 0 45px;
    border-radius: 3px;
    border-left: 5px solid #629A9C;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.07);
    }

    ol li {
    cursor: move;
    }

    ul li {
    border-left: 5px solid #999;
    opacity: 0.5;
    }

    li a {
    position: absolute;
    top: 2px;
    right: 5px;
    display: inline-block;
    width: 14px;
    height: 12px;
    border-radius: 14px;
    border: 6px double #FFF;
    background: #CCC;
    line-height: 14px;
    text-align: center;
    color: #FFF;
    font-weight: bold;
    font-size: 14px;
    cursor: pointer;
    }

    footer {
    color: #666;
    font-size: 14px;
    text-align: center;
    }

    footer a {
    color: #666;
    text-decoration: none;
    color: #999;
    }

    @media screen and (max-device-width: 620px) {
    section {
    width: 96%;
    padding: 0 2%;
    }
    }

    @media screen and (min-width: 620px) {
    section {
    width: 600px;
    padding: 0 10px;
    }
    }
    • 本文标题:jQuery笔记
    • 本文作者:馨er
    • 创建时间:2022-07-22 00:29:17
    • 本文链接:https://sjxbbd.vercel.app/2022/07/22/807b8ac47e8f/
    • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!