曾风靡一时的jQuery,你还不会吗?

初识jQuery

在开始jQuery之前,我们先来看一个例子:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	<script src="js/jquery-1.12.3.js" type="text/javascript" charset="utf-8"></script>
		<!-- 使用jQuery实现 -->
		<script type="text/javascript">
			//绑定文档加载完成的监听
			$(function (){
				$('#btn2').click(function (){
				 var username =	$('#username').val()
				 alert(username)
				})
			})
		</script>
	</head>
	<body>
		用户名: <input type="text" name="" id="username" value="" />
		<button type="button" id="btn1">确定(原生版)</button>
		<button type="button" id="btn2">确定(jQuery版)</button>
	</body>
	<script type="text/javascript">
		//使用原生DOM
		window.onload = function (){
			var btn1 = document.getElementById('btn1')
			btn1.onclick = function () {
				var username = document.getElementById('username').value
				alert(username)
			}
		}
	</script>
</html>

这是分别使用原生JS和jQuery来实现的一个小功能,好像看起来jQuery还麻烦一点,但是代码量大了之后,jQuery还是要优于原生JS的
下面,我们从3个方面了解什么是jQuery

  1. what?
    jQuery是什么呢?
    它是一个优秀的JS函数库,封装简化DOM操作(CURD)/Ajax,它倡导的理念是"write less do more!"
  2. why?
    我们为什么要用jQuery呢?
    这就要说到jQuery的特点:
  • 强大的选择器:方便快速查找DOM元素
  • 隐式遍历(迭代):一次操作多个元素
  • 读写合一:读数据和写数据用的是一个函数
  • 事件处理
  • 链式调用
  • DOM操作(CURD)
  • 样式操作
  1. how?
    那我们该如何使用jQuery呢?

引入jQuery库

  • 本地引入:使用script标签将本地的jQuery文件引入项目使用
  • CDN远程引入
  • npm下载:执行 npm install jQuery --save,下载jQuery并添加到项目依赖

使用jQuery

  • 使用jQuery核心函数:$()/jQuery()
  • 使用jQuery核心对象:$xxx(执行$()得到的返回对象)

jQuery的两把利器

jQuery中最重要的就是jQuery的两把利器,jQuery函数和jQuery对象,下面我分别介绍

  1. jQuery函数
    jQuery库向外暴露的就是jQuery函数,可以通过$()/jQuery()的方式直接使用,但是也要分情况使用,它里面柔和了太多的功能,使用的方式不同,达到的效果就不同

当成一般函数使用,根据传入的参数有以下用法:$(param)

  • param是function:相当于window.οnlοad=function(){},文档加载完成后的监听
  • param是选择器字符串:查找所有匹配的DOM元素,返回包含所有DOM元素的jQuery对象
  • param是DOM元素:将DOM元素包装成jQuery对象返回,通常使用$(this)
  • param是标签字符串:创建标签DOM元素对象,并包装成jQuery对象返回

当成对象使用:可以调用里面的一些方法

  • .each(obj/arr,function(key/index,value/item){})
  • .trim(str)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="">
			<button type="button" id="btn">测试</button>
			<br>
			
			<input type="text" name="msg1" />
			<input type="text" name="msg2" />
		</div>
	</body>
	<script src="js/jquery-1.12.3.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		/*
		需求1:点击按钮:显式按钮的文本,显式一个新的输入框
		需求2:遍历输出数组中所有元素
		需求3:去掉"my cxq "两端的空格
		*/
	   //1.参数为函数:当DOM加载完成后,执行此回调函数
	   $(function (){ //绑定文档加载完成的监听
		   //2.参数为选择器字符串:查找所有匹配的标签,并将他们封装成jQuery对象
		   $('#btn').click(function (){
			   //this是发生事件的dom元素----->button
			   //alert(this.innerHTML)
			   //3.参数为DOM元素:将dom对象包装成jQuery对象
			   alert($(this).html())
			   
			   //4.参数为html标签字符串(用得少):创建标签对象并封装成jQuery对象
			   $('<input type="text" name="msg3" id="" value="" />').appendTo('div')
		   })
	   })
	   
		var arr = [2,4,7]
		$.each(arr,function (index,item){
			console.log(index,item)
		})
		var str = '  my cxq  '
		console.log($.trim(str))
	</script>
</html>
  1. jQuery对象
    包含所有匹配的n个DOM元素的伪数组对象
    执行$()返回的就是jQuery对象

基本行为:

  • length/size():得到DOM元素的个数
  • [index]/get(index):得到指定下边对应的DOM元素
  • each(function(index,domEle){}):遍历所有DOM元素
  • index():得到当前DOM元素在所有兄弟中的下标并返回
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button type="button">测试1</button>
		<button type="button">测试2</button>
		<button type="button" id="btn3">测试3</button>
		<button type="button">测试4</button>
		<!-- 
		 1.jQuery对象是一个包含所有匹配的任意多个dom元素的伪数组对象
		 2.基本行为
			*size()/length
			*[index]/get(index):得到对应位置的DOM元素
			*each():遍历包含的所有DOM元素
			*index():得到在所在兄弟元素中的下标
		 -->
	</body>
	<script src="js/jquery-1.12.3.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		//需求1:统计一共有多少个按钮
		var $buttons = $('button')
		console.log($buttons.size(),$buttons.length)
		
		//需求2:取出第二个button
		console.log($buttons[1].innerHTML)
		console.log($buttons.get(1).innerHTML)
		
		//需求3:输出所有button标签的文本
		$buttons.each(function (index,domEle){
			console.log(index,domEle.innerHTML,this)
		})
		//需求4:输出测试3按钮是所有按钮的第几个?
		console.log($('#btn3').index())
	</script>
</html>

jQuery 选择器

选择器本身只是一个有特定语法规则的字符串,没有实质作用,它的基本语法规则使用的就是CSS的选择器语法,只有调用$(),并将选择器作为参数传入才能起作用,它有以下分类:

  1. 基本选择器
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>05_基本选择器</title>
</head>

<body>
<div id="div1" class="box">div1(class="box")</div>
<div id="div2" class="box">div2(class="box")</div>
<div id="div3">div3</div>
<span class="box">span(class="box")</span>

<br>
<ul>
  <li>AAAAA</li>
  <li title="hello">BBBBB(title="hello")</li>
  <li class="box">CCCCC(class="box")</li>
  <li title="hello">DDDDDD(title="hello")</li>
</ul>

<!--
1. 是什么?
  - 有特定格式的字符串
2. 作用
  - 用来查找特定页面元素
3. 基本选择器
  - #id : id选择器
  - element : 元素选择器
  - .class : 属性选择器
  - * : 任意标签
  - selector1,selector2,selectorN : 取多个选择器的并集(组合选择器)
  - selector1selector2selectorN : 取多个选择器的交集(相交选择器)
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
  /*
   需求:
   1. 选择id为div1的元素
   2. 选择所有的div元素
   3. 选择所有class属性为box的元素
   4. 选择所有的div和span元素
   5. 选择所有class属性为box的div元素
   */
  //1. 选择id为div1的元素
  // $('#div1').css('background', 'red')

  //2. 选择所有的div元素
  // $('div').css('background', 'red')

  //3. 选择所有class属性为box的元素
  //$('.box').css('background', 'red')

  //4. 选择所有的div和span元素
  // $('div,span').css('background', 'red')

  //5. 选择所有class属性为box的div元素
  //$('div.box').css('background', 'red')

  //$('*').css('background', 'red')

</script>
</body>

</html>
  1. 层次选择器
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>06_层次选择器</title>
</head>

<body>
<ul>
  <li>AAAAA</li>
  <li class="box">CCCCC</li>
  <li title="hello"><span>BBBBB</span></li>
  <li title="hello"><span class="box">DDDD</span></li>
  <span>EEEEE</span>
</ul>

<!--
层次选择器: 查找子元素, 后代元素, 兄弟元素的选择器
1. ancestor descendant
  在给定的祖先元素下匹配所有的后代元素
2. parent>child
  在给定的父元素下匹配所有的子元素
3. prev+next
  匹配所有紧接在 prev 元素后的 next 元素
4. prev~siblings
  匹配 prev 元素之后的所有 siblings 元素
-->

<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
  /*
   需求:
   1. 选中ul下所有的的span
   2. 选中ul下所有的子元素span
   3. 选中class为box的下一个li
   4. 选中ul下的class为box的元素后面的所有兄弟元素
   */

  //1. 选中ul下所有的的span
  // $('ul span').css('background', 'yellow')

  //2. 选中ul下所有的子元素span
  // $('ul>span').css('background', 'yellow')

  //3. 选中class为box的下一个li
  // $('.box+li').css('background', 'yellow')

  //4. 选中ul下的class为box的元素后面的所有兄弟元素
  $('ul .box~*').css('background', 'yellow')
</script>
</body>
</html>
  1. 过滤选择器
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>07_过滤选择器</title>
</head>

<body>

<div id="div1" class="box">class为box的div1</div>
<div id="div2" class="box">class为box的div2</div>
<div id="div3">div3</div>
<span class="box">class为box的span</span>
<br/>
<ul>
  <li>AAAAA</li>
  <li title="hello">BBBBB</li>
  <li class="box">CCCCC</li>
  <li title="hello">DDDDDD</li>
  <li title="two">BBBBB</li>
  <li style="display:none">我本来是隐藏的</li>
</ul>
<!--
在原有选择器匹配的元素中进一步进行过滤的选择器
  * 基本
  * 内容
  * 可见性
  * 属性
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">

  /*
   需求:
   1. 选择第一个div
   2. 选择最后一个class为box的元素
   3. 选择所有class属性不为box的div
   4. 选择第二个和第三个li元素
   5. 选择内容为BBBBB的li
   6. 选择隐藏的li
   7. 选择有title属性的li元素
   8. 选择所有属性title为hello的li元素
   */
  //1. 选择第一个div
  // $('div:first').css('background', 'red')

  //2. 选择最后一个class为box的元素
  //$('.box:last').css('background', 'red')

  //3. 选择所有class属性不为box的div
  // $('div:not(.box)').css('background', 'red')  //没有class属性也可以

  //4. 选择第二个和第三个li元素
  // $('li:gt(0):lt(2)').css('background', 'red') // 多个过滤选择器不是同时执行, 而是依次
  //$('li:lt(3):gt(0)').css('background', 'red')

  //5. 选择内容为BBBBB的li
  // $('li:contains("BBBBB")').css('background', 'red')

  //6. 选择隐藏的li
  // console.log($('li:hidden').length, $('li:hidden')[0])

  //7. 选择有title属性的li元素
  // $('li[title]').css('background', 'red')

  //8. 选择所有属性title为hello的li元素
  $('li[title="hello"]').css('background', 'red')

</script>
</body>

</html>
  1. 表单选择器
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>08_表单选择器</title>
</head>

<body>
<form>
  用户名: <input type="text"/><br>
  密 码: <input type="password"/><br>
  爱 好:
  <input type="checkbox" checked="checked"/>篮球
  <input type="checkbox"/>足球
  <input type="checkbox" checked="checked"/>羽毛球 <br>
  性 别:
  <input type="radio" name="sex" value='male'/><input type="radio" name="sex" value='female'/><br>
  邮 箱: <input type="text" name="email" disabled="disabled"/><br>
  所在地:
  <select>
    <option value="1">北京</option>
    <option value="2" selected="selected">天津</option>
    <option value="3">河北</option>
  </select><br>
  <input type="submit" value="提交"/>
</form>
<!--
表单选择器
  1). 表单
  2). 表单对象属性
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
  /*
   需求:
   1. 选择不可用的文本输入框
   2. 显示选择爱好 的个数
   3. 显示选择的城市名称
   */
  //1. 选择不可用的文本输入框
  // $(':text:disabled').css('background', 'red')

  //2. 显示选择爱好 的个数
  console.log($(':checkbox:checked').length)

  //3. 显示选择的城市名称
  $(':submit').click(function () {
    var city = $('select>option:selected').html() // 选择的option的标签体文本
    city = $('select').val()  // 选择的option的value属性值
    alert(city)


  })

</script>
</body>
</html>

$工具的方法

这些方法很少用了,因为后面出现了更好的并且已经集成到JS中了,看一下吧

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>09_$工具方法</title>
</head>
<body>
<!--
1. $.each(): 遍历数组或对象中的数据
2. $.trim(): 去除字符串两边的空格
3. $.type(obj): 得到数据的类型
4. $.isArray(obj): 判断是否是数组
5. $.isFunction(obj): 判断是否是函数
6. $.parseJSON(json) : 解析json字符串转换为js对象/数组
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
  //1. $.each(): 遍历数组或对象中的数据
  var obj = {
    name: 'Tom',
    setName: function (name) {
      this.name = name
    }
  }
  $.each(obj, function (key, value) {
    console.log(key, value)
  })
  
  //2. $.trim(): 去除字符串两边的空格
  //3. $.type(obj): 得到数据的类型
  console.log($.type($)) // 'function'

  //4. $.isArray(obj): 判断是否是数组
  console.log($.isArray($('body')), $.isArray([])) // false true
  //5. $.isFunction(obj): 判断是否是函数
  console.log($.isFunction($)) // true
  //6. $.parseJSON(json) : 解析json字符串转换为js对象/数组
  var json = '{"name":"Tom", "age":12}'  // json对象: {}
  // json对象===>JS对象
  console.log($.parseJSON(json))
  json = '[{"name":"Tom", "age":12}, {"name":"JACK", "age":13}]' // json数组: []
  // json数组===>JS数组
  console.log($.parseJSON(json))
  /*
  JSON.parse(jsonString)   json字符串--->js对象/数组
  JSON.stringify(jsObj/jsArr)  js对象/数组--->json字符串
  */
</script>
</body>
</html>

jQuery属性

  1. 操作任意属性
    attr():操作所有非布尔值的属性
    removeAttr():移除属性
    prop():操作布尔值类型的数据
  2. 操作class属性
    addClass():添加一个class属性值,不会覆盖原来的
    removeClass():移除指定的class值
  3. 操作HTML代码/文本/值
    html():文本值
    val():value属性值
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>10_属性</title>
</head>
<body>

<div id="div1" class="box" title="one">class为box的div1</div>
<div id="div2" class="box" title="two">class为box的div2</div>
<div id="div3">div3</div>
<span class="box">class为box的span</span>
<br/>
<ul>
  <li>AAAAA</li>
  <li title="hello" class="box2">BBBBB</li>
  <li class="box">CCCCC</li>
  <li title="hello">DDDDDD</li>
  <li title="two"><span>BBBBB</span></li>
</ul>

<input type="text" name="username" value="guiguClass"/>
<br>
<input type="checkbox">
<input type="checkbox">
<br>
<button>选中</button>
<button>不选中</button>

<!--
1. 操作任意属性
   attr()
   removeAttr()
   prop()
2. 操作class属性
   addClass()
   removeClass()
3. 操作HTML代码/文本/html()
   val()
-->

<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
  /*
   需求:
   1. 读取第一个div的title属性
   2. 给所有的div设置name属性(value为atguigu)
   3. 移除所有div的title属性
   4. 给所有的div设置class='guiguClass'
   5. 给所有的div添加class='abc'
   6. 移除所有div的guiguClass的class
   7. 得到最后一个li的标签体文本
   8. 设置第一个li的标签体为"<h1>mmmmmmmmm</h1>"
   9. 得到输入框中的value值
   10. 将输入框的值设置为atguigu
   11. 点击'全选'按钮实现全选
   12. 点击'全不选'按钮实现全不选
   */
  //1. 读取第一个div的title属性
  // console.log($('div:first').attr('title')) // one

  //2. 给所有的div设置name属性(value为cxq)
  // $('div').attr('name', 'cxq')

  //3. 移除所有div的title属性
  // $('div').removeAttr('title')

  //4. 给所有的div设置class='cxqClass'
  //$('div').attr('class', 'cxqClass')

  //5. 给所有的div添加class='abc'
  //$('div').addClass('abc')

  //6. 移除所有div的cxqClass的class
  //$('div').removeClass('cxqClass')

  //7. 得到最后一个li的标签体文本
  //console.log($('li:last').html())

  //8. 设置第一个li的标签体为"<h1>mmmmmmmmm</h1>"
  //$('li:first').html('<h1>mmmmmmmmm</h1>')

  //9. 得到输入框中的value值
  //console.log($(':text').val()) // 读取

  //10. 将输入框的值设置为cxq
  //$(':text').val('cxq') // 设置      读写合一
  //11. 点击'全选'按钮实现全选
    // attr(): 操作属性值为非布尔值的属性
    // prop(): 专门操作属性值为布尔值的属性
  var $checkboxs = $(':checkbox')
  $('button:first').click(function () {
    $checkboxs.prop('checked', true)
  })

  //12. 点击'全不选'按钮实现全不选
  $('button:last').click(function () {
    $checkboxs.prop('checked', false)
  })
</script>
</body>
</html>

CSS模块

接下来我们谈一谈关于css()函数设置样式、位置和尺寸的API
css()

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>11_css</title>
</head>
<body>
<p style="color: blue;">月亮的后裔</p>
<p style="color: green;">太阳的后裔</p>

<!--
设置css样式/读取css值
  css()
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
  /*
   1. 得到第一个p标签的颜色
   2. 设置所有p标签的文本颜色为red
   3. 设置第2个p的字体颜色(#ff0011),背景(blue),宽(300px), 高(30px)
   */
  //1. 得到第一个p标签的颜色
  //console.log($('p:first').css('color'))

  //2. 设置所有p标签的文本颜色为red
  //$('p').css('color', 'red')

  //3. 设置第2个p的字体颜色(#ff0011),背景(blue),宽(300px), 高(30px)
  $('p:eq(1)').css({
    color: '#ff0011',
    background: 'blue',
    width: 300,
    height: 30
  })

</script>
</body>
</html>

offset和position

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>12_offset和position</title>
</head>
<style type="text/css">
  * {
    margin: 0px;
  }

  .div1 {
    position: absolute;
    width: 200px;
    height: 200px;
    top: 20px;
    left: 10px;
    background: blue;
  }

  .div2 {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50px;
    background: red;
  }

  .div3 {
    position: absolute;
    top: 250px;
  }
</style>
<body style="height: 2000px;">

<div class="div1">
  <div class="div2">测试offset</div>
</div>

<div class='div3'>
  <button id="btn1">读取offset和position</button>
  <button id="btn2">设置offset</button>
</div>

<!--
获取/设置标签的位置数据
  * offset(): 相对页面左上角的坐标
  * position(): 相对于父元素左上角的坐标
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
  /*
  需求:
  1. 点击 btn1
    打印 div1 相对于页面左上角的位置
    打印 div2 相对于页面左上角的位置
    打印 div1 相对于父元素左上角的位置
    打印 div2 相对于父元素左上角的位置
  2. 点击 btn2
    设置 div2 相对于页面的左上角的位置
   */
  $('#btn1').click(function () {
//    打印 div1 相对于页面左上角的位置
    var offset = $('.div1').offset()
    console.log(offset.left, offset.top) // 10 20
//    打印 div2 相对于页面左上角的位置
    offset = $('.div2').offset()
    console.log(offset.left, offset.top) // 10 70
//    打印 div1 相对于父元素左上角的位置
    var position = $('.div1').position()
    console.log(position.left, position.top) // 10 20
//    打印 div2 相对于父元素左上角的位置
    position = $('.div2').position()
    console.log(position.left, position.top) // 0 50
  })

  $('#btn2').click(function () {
    $('.div2').offset({
      left: 50,
      top: 100
    })
  })
</script>
</body>
</html>

元素滚动

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>13_元素滚动</title>
</head>
<body style="height: 2000px;">
<div style="border:1px solid black;width:100px;height:150px;overflow:auto">
  This is some text. This is some text. This is some text. This is some text.
  This is some text. This is some text. This is some text. This is some text.
  This is some text. This is some text. This is some text. This is some text.
  This is some text. This is some text. This is some text. This is some text.
  This is some text. This is some text. This is some text. This is some text.
  This is some text. This is some text. This is some text. This is some text.
  his is some text.
</div>
<br>
<br>
<br>
<button id="btn1">得到scrollTop</button>
<button id="btn2">设置scrollTop</button>

<!--
1. scrollTop():
  读取/设置滚动条的Y坐标
2. $(document.body).scrollTop()+$(document.documentElement).scrollTop()
  读取页面滚动条的Y坐标(兼容chrome和IE)
3. $('body,html').scrollTop(60);
  滚动到指定位置(兼容chrome和IE)
-->
<script src="js/jquery-1.10.1.js"></script>
<script>
  /*
   需求:
   1. 得到div或页面滚动条的坐标
   2. 让div或页面的滚动条滚动到指定位置
   */
  //1. 得到div或页面滚动条的坐标
  $('#btn1').click(function () {
    console.log($('div').scrollTop())
    // console.log($('html').scrollTop()+$('body').scrollTop())
    console.log($(document.documentElement).scrollTop()+$(document.body).scrollTop()) // 兼容IE/Chrome
  })
  //2. 让div或页面的滚动条滚动到指定位置
  $('#btn2').click(function () {
    $('div').scrollTop(200)
    $('html,body').scrollTop(300)
  })
</script>
</body>

</html>

元素的尺寸

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>14_元素的尺寸</title>
</head>
<style>
  div {
    width: 100px;
    height: 150px;
    background: red;
    padding: 10px;
    border: 10px #fbd850 solid;
    margin: 10px;
  }
</style>
</head>

<body>
<div>div</div>

<!--
1. 内容尺寸
  height(): height
  width(): width
2. 内部尺寸
  innerHeight(): height+padding
  innerWidth(): width+padding
3. 外部尺寸
  outerHeight(false/true): height+padding+border  如果是true, 加上margin
  outerWidth(false/true): width+padding+border 如果是true, 加上margin
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script>
  var $div = $('div')
  // 1. 内容尺寸
  console.log($div.width(), $div.height())  // 100 150
  // 2. 内部尺寸
  console.log($div.innerWidth(), $div.innerHeight()) //120 170
  // 3. 外部尺寸
  console.log($div.outerWidth(), $div.outerHeight()) //140 190
  console.log($div.outerWidth(true), $div.outerHeight(true)) //160 210

</script>
</body>

</html>

jQuery对象的筛选

在jQuery对象中的元素对象数组中过滤出一部分元素来叫做jQuery对象的筛选,常用的API有:

  • .first()
  • . last()
  • . eq(index|-index)
  • . filter(selector)
  • . not(selector)
  • . has(selector)
  • .children(): 子标签中找
  • . find() : 后代标签中找
  • . parent() : 父标签
  • . prevAll() : 前面所有的兄弟标签
  • . nextAll() : 后面所有的兄弟标签
  • . siblings() : 前后所有的兄弟标签
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>15_筛选_过滤</title>
</head>

<body>
<ul>
  <li>AAAAA</li>
  <li title="hello" class="box2">BBBBB</li>
  <li class="box">CCCCC</li>
  <li title="hello">DDDDDD</li>
  <li title="two"><span>BBBBB</span></li>
</ul>
<li>eeeee</li>
<li>EEEEE</li>
<br>

<!--
在jQuery对象中的元素对象数组中过滤出一部分元素来
1. first()
2. last()
3. eq(index|-index)
4. filter(selector)
5. not(selector)
6. has(selector)
-->

<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
  /*
   需求:
   1. ul下li标签第一个
   2. ul下li标签的最后一个
   3. ul下li标签的第二个
   4. ul下li标签中title属性为hello的
   5. ul下li标签中title属性不为hello的
   6. ul下li标签中有span子标签的
   */
  var $lis = $('ul>li')
  //1. ul下li标签第一个
  // $lis.first().css('background', 'red')
  // $lis[0].style.background = 'red'

  //2. ul下li标签的最后一个
  // $lis.last().css('background', 'red')

  //3. ul下li标签的第二个
  // $lis.eq(1).css('background', 'red')

  //4. ul下li标签中title属性为hello的
  // $lis.filter('[title=hello]').css('background', 'red')

  //5. ul下li标签中title属性不为hello的
  // $lis.not('[title=hello]').css('background', 'red')
  // $lis.filter('[title!=hello]').filter('[title]').css('background', 'red')

  //6. ul下li标签中有span子标签的
  $lis.has('span').css('background', 'red')
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>16_筛选_查找孩子-父母-兄弟标签</title>
</head>
<body>
<div id="div1" class="box" title="one">class为box的div1</div>
<div id="div2" class="box">class为box的div2</div>
<div id="div3">div3</div>
<span class="box">class为box的span</span>
<br/>
<div>
  <ul>
    <span>span文本1</span>
    <li>AAAAA</li>
    <li title="hello" class="box2">BBBBB</li>
    <li class="box" id='cc'>CCCCC</li>
    <li title="hello">DDDDDD</li>
    <li title="two"><span>span文本2</span></li>
    <span>span文本3</span>
  </ul>
  <span>span文本444</span><br>
  <li>eeeee</li>
  <li>EEEEE</li>
  <br>
</div>

<!--
在已经匹配出的元素集合中根据选择器查找孩子/父母/兄弟标签
1. children(): 子标签中找
2. find() : 后代标签中找
3. parent() : 父标签
4. prevAll() : 前面所有的兄弟标签
5. nextAll() : 后面所有的兄弟标签
6. siblings() : 前后所有的兄弟标签
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
  /*
   需求:
   1. ul标签的第2个span子标签
   2. ul标签的第2个span后代标签
   3. ul标签的父标签
   4. id为cc的li标签的前面的所有li标签
   5. id为cc的li标签的所有兄弟li标签
   */
  var $ul = $('ul')
  //1. ul标签的第2个span子标签
  //$ul.children('span:eq(1)').css('background', 'red')

  //2. ul标签的第2个span后代标签
  // $ul.find('span:eq(1)').css('background', 'red')

  //3. ul标签的父标签
  // $ul.parent().css('background', 'red')

  //4. id为cc的li标签的前面的所有li标签
  var $li = $('#cc')
  // $li.prevAll('li').css('background', 'red')

  //5. id为cc的li标签的所有兄弟li标签
  $li.siblings('li').css('background', 'red')
</script>
</body>
</html>

jQuery文档处理

在原生JS中,对文档进行增删改,操作过程实在有些繁琐,我们先需要创建一个节点,给节点添加内容,将节点插入到指定的位置,使用的API些许复杂,jQuery中对于的文档的处理相比之下就更简单,也更灵活

  1. 添加/替换元素
  • append(content)
    向当前匹配的所有元素内部的最后插入指定内容
  • prepend(content)
    向当前匹配的所有元素内部的最前面插入指定内容
  • before(content)
    将指定内容插入到当前所有匹配元素的前面
  • after(content)
    将指定内容插入到当前所有匹配元素的后面
  • replaceWith(content)
    用指定内容替换所有匹配的标签
  1. 删除元素
  • empty()
    删除所有匹配元素的子元素
  • remove()
    删除所有匹配的元素
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>17_文档_增删改</title>
</head>
<style type="text/css">
  * {
    margin: 0px;
  }

  .div1 {
    position: absolute;
    width: 200px;
    height: 200px;
    top: 20px;
    left: 10px;
    background: blue;
  }

  .div2 {
    position: absolute;
    width: 100px;
    height: 100px;
    /*top: 50px;*/
    background: red;
  }

  .div3 {
    position: absolute;
    top: 250px;
  }
</style>

<body>
<ul id="ul1">
  <li>AAAAA</li>

  <li title="hello">BBBBB</li>
  <li class="box">CCCCC</li>

  <li title="hello">DDDDDD</li>
  <li title="two">EEEEE</li>
  <li>FFFFF</li>

</ul>
<br>
<br>
<ul id="ul2">
  <li>aaa</li>
  <li title="hello">bbb</li>
  <li class="box">ccc</li>
  <li title="hello">ddd</li>
  <li title="two">eee</li>
</ul>

<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
  /*
   需求:
   1. 向id为ul1的ul下添加一个span(最后)
   2. 向id为ul1的ul下添加一个span(最前)
   3. 在id为ul1的ul下的li(title为hello)的前面添加span
   4. 在id为ul1的ul下的li(title为hello)的后面添加span
   5. 将在id为ul2的ul下的li(title为hello)全部替换为p
   6. 移除id为ul2的ul下的所有li
   */

  //1. 向id为ul1的ul下添加一个span(最后)
  var $ul1 = $('#ul1')
  // $ul1.append('<span>append()添加的span</span>')
  $('<span>appendTo()添加的span</span>').appendTo($ul1)

  //2. 向id为ul1的ul下添加一个span(最前)
  // $ul1.prepend('<span>prepend()添加的span</span>')
  $('<span>prependTo()添加的span</span>').prependTo($ul1)

  //3. 在id为ul1的ul下的li(title为hello)的前面添加span
  $ul1.children('li[title=hello]').before('<span>before()添加的span</span>')

  //4. 在id为ul1的ul下的li(title为hello)的后面添加span
  $ul1.children('li[title=hello]').after('<span>after()添加的span</span>')

  //5. 将在id为ul2的ul下的li(title为hello)全部替换为p
  $('#ul2>li[title=hello]').replaceWith('<p>replaceAll()替换的p</p>')
  //6. 移除id为ul2的ul下的所有li
  // $('#ul2').empty()  // <p>也会删除
  $('#ul2>li').remove()
</script>
</body>
</html>

事件

  1. 事件绑定(2种)
  • eventName(function(){})
    绑定对应事件名的监听, 例如:$(’#div’).click(function(){});
  • on(eventName, funcion(){})
    通用的绑定事件监听, 例如:$(’#div’).on(‘click’, function(){})
  • 优缺点:
    eventName: 编码方便, 但只能加一个监听, 且有的事件监听不支持
    on: 编码不方便, 可以添加多个监听, 且更通用
  1. 事件解绑
  • off(eventName)
  1. 事件的坐标
  • event.clientX, event.clientY 相对于视口的左上角
  • event.pageX, event.pageY 相对于页面的左上角
  • event.offsetX, event.offsetY 相对于事件元素左上角
  1. 事件相关处理
  • 停止事件冒泡 : event.stopPropagation()
  • 阻止事件默认行为 : event.preventDefault()
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>18_事件绑定与解绑</title>
</head>
<style type="text/css">
  * {
    margin: 0px;
  }

  .out {
    position: absolute;
    width: 200px;
    height: 200px;
    top: 20px;
    left: 10px;
    background: blue;
  }

  .inner {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50px;
    background: red;
  }

  .divBtn {
    position: absolute;
    top: 250px;
  }

</style>

<body style="height: 2000px;">

<div class="out">
  外部DIV
  <div class="inner">内部div</div>
</div>

<div class='divBtn'>
  <button id="btn1">取消绑定所有事件</button>
  <button id="btn2">取消绑定mouseover事件</button>
  <button id="btn3">测试事件坐标</button>
  <a href="http://www.baidu.com" id="test4">百度一下</a>
</div>

<script src="js/jquery-1.10.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
  /*
   需求:
   1. 给.out绑定点击监听(用两种方法绑定)
   2. 给.inner绑定鼠标移入和移出的事件监听(用3种方法绑定)
   3. 点击btn1解除.inner上的所有事件监听
   4. 点击btn2解除.inner上的mouseover事件
   5. 点击btn3得到事件坐标
   6. 点击.inner区域, 外部点击监听不响应
   7. 点击链接, 如果当前时间是偶数不跳转
   */
  //1. 给.out绑定点击监听(用两种方法绑定)
  /*$('.out').click(function () {
   console.log('click out')
   })*/
  $('.out').on('click', function () {
    console.log('on click out')
  })

  //2. 给.inner绑定鼠标移入和移出的事件监听(用3种方法绑定)
  /*
   $('.inner')
   .mouseenter(function () { // 进入
    console.log('进入')
   })
   .mouseleave(function () { // 离开
   console.log('离开')
   })
   */
  /*
   $('.inner')
   .on('mouseenter', function () {
   console.log('进入2')
   })
   .on('mouseleave', function () {
   console.log('离开2')
   })
   */
  $('.inner').hover(function () {
    console.log('进入3')
  }, function () {
    console.log('离开3')
  })


  //3. 点击btn1解除.inner上的所有事件监听
  $('#btn1').click(function () {
    $('.inner').off()
  })

  //4. 点击btn2解除.inner上的mouseenter事件
  $('#btn2').click(function () {
    $('.inner').off('mouseenter')
  })

  //5. 点击btn3得到事件坐标
  $('#btn3').click(function (event) { // event事件对象
    console.log(event.offsetX, event.offsetY) // 原点为事件元素的左上角
    console.log(event.clientX, event.clientY) // 原点为视口的左上角
    console.log(event.pageX, event.pageY) // 原点为页面的左上角
  })

  //6. 点击.inner区域, 外部点击监听不响应
  $('.inner').click(function (event) {
    console.log('click inner')
    //停止事件冒泡
    event.stopPropagation()
  })
  
  //7. 点击链接, 如果当前时间是偶数不跳转
  $('#test4').click(function (event) {
    if(Date.now()%2===0) {
      event.preventDefault()
    }
  })
</script>
</body>
</html>

5.事件委托(委派/代理)
在开始事件委托之前,我们来看一个例子

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="UTF-8">
  <title>20_事件委托_引入.html</title>
</head>

<body>

<ul>
  <li>11111</li>
  <li>1111111</li>
  <li>111111111</li>
  <li>11111111111</li>
</ul>

<li>22222</li>
<br>
<button id="btn">添加新的li</button>
<br>

<!--
绑定事件监听的问题: 新加的元素没有监听
-->
<script src="js/jquery-1.10.1.js"></script>
<script>
  /*
   需求:
   1. 点击 li 背景就会变为红色
   2. 点击 btn 就添加一个 li
  */
  $('ul>li').click(function () {
    this.style.background = 'red'
  })

  $('#btn').click(function () {
    $('ul').append('<li>新增的li....</li>')
  })
</script>
</body>
</html>

  1. 事件委托(委派/代理):
  • 将多个子元素(li)的事件监听委托给父辈元素(ul)处理
  • 监听回调是加在了父辈元素上
  • 当操作任何一个子元素(li)时, 事件会冒泡到父辈元素(ul)
  • 父辈元素不会直接处理事件, 而是根据event.target得到发生事件的子元素(li), 通过这个子元素调用事件回调函数
  1. 事件委托的2方:
  • 委托方: 业主 li
  • 被委托方: 中介 ul
  1. 使用事件委托的好处
  • 添加新的子元素, 自动有事件响应处理
  • 减少事件监听的数量: n==>1
  1. jQuery的事件委托API
  • 设置事件委托: $(parentSelector).delegate(childrenSelector, eventName, callback)
  • 移除事件委托: $(parentSelector).undelegate(eventName)

我们使用事件委托改进上面的例子

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="UTF-8">
  <title>20_事件委托2</title>
</head>

<body>
<ul>
  <li>1111</li>
  <li>2222</li>
  <li>3333</li>
  <li>4444</li>
</ul>

<li>22222</li>
<br>
<button id="btn1">添加新的li</button>
<button id="btn2">删除ul上的事件委托的监听器</button>

<script src="js/jquery-1.10.1.js"></script>
<script>
  // 设置事件委托
  $('ul').delegate('li', 'click', function () {
    // console.log(this)
    this.style.background = 'red'
  })

  $('#btn1').click(function () {
    $('ul').append('<li>新增的li....</li>')
  })

  $('#btn2').click(function () {
    // 移除事件委托
    $('ul').undelegate('click')
  })

</script>
</body>
</html>

效果

jQuery中提供了很多关于效果的API,但是已经很少使用了,CSS3的transform和animation属性可以完成几乎jQuery提供的全部动画的API,我就例一下吧,就不举例子了:

淡入淡出: 不断改变元素的透明度(opacity)来实现的

  1. fadeIn(): 带动画的显示
  2. fadeOut(): 带动画隐藏
  3. fadeToggle(): 带动画切换显示/隐藏

滑动动画: 不断改变元素的高度实现

  1. slideDown(): 带动画的展开
  2. slideUp(): 带动画的收缩
  3. slideToggle(): 带动画的切换展开/收缩

显示隐藏,默认没有动画, 动画(opacity/height/width)

  1. show(): (不)带动画的显示
  2. hide(): (不)带动画的隐藏
  3. toggle(): (不)带动画的切换显示/隐藏

jQuery动画本质 : 在指定时间内不断改变元素样式值来实现的

  1. animate(): 自定义动画效果的动画
  2. stop(): 停止动画

多库共存

JS封装的函数库对$这个符号做了特殊的解释,使得它拥有了特别的功能,但是如果项目中有其他库也对$做了特殊的解释,这会产生多库共存的冲突,导致$失效,为了解决这个问题,jQuery想出了办法:
jQuery库可以释放$的使用权, 让另一个库可以正常使用, 此时jQuery库只能使用jQuery了

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>26_多库共存</title>
  <style type="text/css">
    * {
      margin: 0px;
    }

    .div1 {
      position: absolute;
      width: 100px;
      height: 100px;
      top: 50px;
      left: 10px;
      background: red;
    }
  </style>
</head>
<body>
<!--
问题 : 如果有2个库都有$, 就存在冲突
解决 : jQuery库可以释放$的使用权, 让另一个库可以正常使用, 此时jQuery库只能使用jQuery了
API : jQuery.noConflict()
-->
<script type="text/javascript" src="js/myLib.js"></script>
<script type="text/javascript" src="js/jquery-1.10.1.js"></script>
<script type="text/javascript">

  // 释放$的使用权
  jQuery.noConflict()
  // 调用myLib中的$
  $()
  // 要想使用jQuery的功能, 只能使用jQuery
  jQuery(function () {
    console.log('文档加载完成')
  })
  console.log('+++++')

</script>
</body>
</html>

onload和ready

$(function(){})其实是$(document).ready(function(){})的缩写,我前面说过这样写等于是加载文档完成时的监听,也就是window.onload,但实际上他们是有区别的:

  • window.onload
    • 包括页面的图片加载完后才会回调(晚)
    • 只能有一个监听回调
  • $(document).ready()
    • 等同于: $(function(){})
    • 页面加载完就回调(早)
    • 可以有多个监听回调
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>window.onload与$(document).ready()</title>
</head>
<body>
<h1>测试window.onload与$(document).ready()</h1>
<img id="logo" src="https://gss0.bdstatic.com/5bVWsj_p_tVS5dKfpU_Y_D3/res/r/image/2017-05-19/6fec71d56242b74eb24b4ac80b817eac.png">

<script type="text/javascript" src="js/jquery-1.10.1.js"></script>
<script type="text/javascript">
  /*
   需求:
   1. 直接打印img的宽度,观察其值
   2. 在 $(function(){}) 中 打印 img 的宽度
   3. 在 window.onload 中打印宽度
   4. 在 img 加载完成后打印宽度
   */

  // 1. 直接打印img的宽度,观察其值
  console.log('直接', $('#logo').width())
  
  window.onload = function () {
    console.log('onload', $('#logo').width())
  }
  window.onload = function () {
    console.log('onload2', $('#logo').width())
  }
  
  $(function () {
    console.log('ready', $('#logo').width())
  })
  $(function () {
    console.log('ready2', $('#logo').width())
  })
  
  $('#logo').on('load', function () {
    console.log('img load', $(this).width())
  })

  /*$(document).ready(function () {

  })*/
  
</script>
</body>
</html>

jQuery插件

插件其实就是基于jQuery编写的扩展库,jQuery插件依赖于jQuery,jQuery插件众多,使用方法各异,我就不一一例举了,合理的使用jQuery插件可以帮助你的开发,详情可以访问jQuery官方的插件库:链接
这里我们讲一下关于扩展插件的方法

  1. 扩展jQuery核心函数的工具方法
    $.extend(object)
  2. 扩展jQuery核心对象的方法
    $.fn.extend(object)
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>25_扩展插件</title>
  <style type="text/css">
    * {
      margin: 0px;
    }

    .div1 {
      position: absolute;
      width: 100px;
      height: 100px;
      top: 50px;
      left: 10px;
      background: red;
    }
  </style>
</head>
<body>
<input type="checkbox" name="items" value="足球"/>足球
<input type="checkbox" name="items" value="篮球"/>篮球
<input type="checkbox" name="items" value="羽毛球"/>羽毛球
<input type="checkbox" name="items" value="乒乓球"/>乒乓球
<br/>
<input type="button" id="checkedAllBtn" value="全 选"/>
<input type="button" id="checkedNoBtn" value="全不选"/>
<input type="button" id="reverseCheckedBtn" value="反选"/>

<!--
1. 扩展jQuery的工具方法
  $.extend(object)
2. 扩展jQuery对象的方法
  $.fn.extend(object)
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript" src="js/my_jQuery-plugin.js"></script>
<script type="text/javascript">
  /*
   需求:
   1. 给 $ 添加4个工具方法:
     * min(a, b) : 返回较小的值
     * max(c, d) : 返回较大的值
     * leftTrim() : 去掉字符串左边的空格
     * rightTrim() : 去掉字符串右边的空格
   2. 给jQuery对象 添加3个功能方法:
     * checkAll() : 全选
     * unCheckAll() : 全不选
     * reverseCheck() : 全反选
   */
  console.log($.min(3, 5), $.max(3, 5))
  var string = '   my atguigu    '
  console.log('-----' + $.leftTrim(string) + '-----')
  console.log('-----' + $.rightTrim(string) + '-----')

  var $items = $(':checkbox[name=items]')
  $('#checkedAllBtn').click(function () {
    $items.checkAll()
  })
  $('#checkedNoBtn').click(function () {
    $items.unCheckAll()
  })
  $('#reverseCheckedBtn').click(function () {
    $items.reverseCheck()
  })
</script>
</body>
</html>

my_jQuery-plugin.js

/*
 需求:
 1. 给 $ 添加4个工具方法:
   * min(a, b) : 返回较小的值
   * max(c, d) : 返回较大的值
   * leftTrim() : 去掉字符串左边的空格
   * rightTrim() : 去掉字符串右边的空格
 2. 给jQuery对象 添加3个功能方法:
 * checkAll() : 全选
 * unCheckAll() : 全不选
 * reverseCheck() : 全反选
 */
(function () {

  // 扩展$的方法
  $.extend({
    min: function (a, b) {
      return a < b ? a : b
    },
    max: function (a, b) {
      return a > b ? a : b
    },
    leftTrim: function (str) {
      return str.replace(/^\s+/, '')
    },
    rightTrim: function (str) {
      return str.replace(/\s+$/, '')
    }
  })

  // 扩展jQuery对象的方法
  $.fn.extend({
    checkAll: function () {
      this.prop('checked', true) // this是jQuery对象
    },
    unCheckAll: function () {
      this.prop('checked', false)
    },
    reverseCheck: function () {
      // this是jQuery对象
      this.each(function () {
        // this是dom元素
        this.checked = !this.checked
      })
    }
  })

})()

好了,我的分享就到这里了,谢谢大家!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值