1.jQuery入门
1.1jQuery介绍
jQuery是一个Javascript库,是对于ECMAScript、dom、bom的一个浅封装,让用户更方便操作。 jQuery功能: 使用CSS选择器进行元素查询
事件机制
Dom操作
属性操作
工具方法
Ajax
jQuery库包含以下功能:
-
HTML选取
-
HTML元素操作
-
CSS操作
-
HTML事件函数
-
JavaScript特效和函数
-
HTML DOM遍历和修改
-
AJAX
1.2jQuery安装
jQuery安装十分简单,只需要将jQuery的库导入到html中即可,我们可以下载下来也可以使用CDN资源。 一般我们在下载或者使用cdn资源的时候,都会让我们选择jquery.js 与 jquery.min.js版本,它们的区别在于jquery.min.js是经过压缩的,体积更小,适用于部署环境。而jquery适用于源码研究,我们对于jquery的学习,应该要上升到源码层次。
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
-
网页中添加jQuery
-
从jquery.com下载jQuery库
-
从CDN中载入jQuery
-
-
下载jQuery
有两个版本的jQuery可供下载:
-
Production version -用于实际的网站中,已被精简和压缩
-
Development version -用于测试和开发(未压缩,是可读的代码)
以上两个版本都可以在jQuery官网下载
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>01-HelloWorld.html</title>
<!-- 本地引入 将jQuery库中的代码放到一个本地文件中-->
<script src="../../jquery-3.5.1/jquery-3.5.1.js"></script>
<!-- 通过cdn引入 -->
<!--
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
-->
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
// console.log($,'jquery函数',typeof $);
// console.log($(),'jquery对象',typeof $());
// console.log($() instanceof Object);
window.onload=function(){
var div=document.getElementsByTagName('div')[0];
console.log(div);
}
// 入口函数
// 等待文档加载完毕再执行代码
$(document).ready(function(){
console.log($('div'));
})
</script>
</head>
<body>
<div>我是一个div</div>
</body>
</html>
上面例子中的入口函数和原生JS中的onload这个函数的作用是一样的
2.jQuery函数
通过"jQuery"和"$"来调用jQuery函数
$(选择器) :通过选择器选择到符合条件的Element元素,将其保存到jQuery对象
$(html片段) :将html片段转换成Element元素,然后再封装成一个jQuery对象
$(Element元素): 将Element元素转换成一个jQuery对象
$(匿名函数): 匿名函数在文档加载完毕以后执行
2.1 jQuery与原生JS的比较
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 本地引入 -->
<script src="./1-jquery.js"></script>
<script>
// 原生js 给每一个标签添加不同的样式
// window.onload=function(){
// var div1=document.getElementsByTagName('div')[0];
// var div2=document.getElementById('one');
// var div3=document.getElementsByClassName('two')[0];
// div1.style.backgroundColor='red';
// div2.style.backgroundColor='yellow';
// div3.style.backgroundColor='blue';
// }
// jquery
$(document).ready(function(){
var div1=$('div:first');
var div2=$('#one');
var div3=$('.two');
console.log($().__proto__===jQuery.prototype);
div1.css('backgroundColor','red');
div2.css({
backgroundColor:'blue',
fontSize:'28px',
fontFamily:"楷体"
});
div3.css({
backgroundColor:"yellow"
})
})
</script>
</head>
<body>
<div>我是一个div</div>
<div id="one">我是一个div</div>
<div class="two">我是一个div</div>
</body>
</html>
与原生JS相比jQuery的操作更加简便
2.2 JS和jQuery入口函数的区别
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js和jquery入口函数的区别</title>
<script src="./1-jquery.js"></script>
<script>
//
// window.onload=function(){
// var img=document.getElementsByTagName('img')[0];
// // js使用window方法获取标签的所有属性
// console.log(window.getComputedStyle(img).width);
// console.log(window.getComputedStyle(img).height);
// }
// 等文档加载完毕执行代码 等同window.onload
// $(function(){
// var img=$('img:first');
// console.log(img.width());
// console.log(img.height());
// })
// 原生js的入口函数 只会执行一个 后面的会覆盖掉前面的
// window.onload=function(){
// alert('我是入口函数1')
// }
// window.onload=function(){
// alert('我是入口函数2')
// }
// jquery的入口函数 入口函数依次执行
// $(function(){
// alert('我是入口函数1')
// });
// $(function(){
// alert('我是入口函数2')
// });
// 2.区别 jquery入口函数四种写法
$(document).ready(function(){
alert('我是入口函数1')
});
jQuery(document).ready(function(){
alert('我是入口函数2')
});
$(function(){
alert("我是入口函数3,推荐写法")
})
jQuery(function(){
alert("我是入口函数4")
})
</script>
</head>
<body>
<!-- 需求:要求获取网络图片的宽高 -->
<!-- <img src="https://img1.baidu.com/it/u=3217543765,3223180824&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1661619600&t=f2c3b255ba98fd782956e21478644f26" alt=""> -->
</body>
</html>
2.3jQuery核心函数和核心对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!--
1.jQuery核心函数作为一般函数调用的时候:$(param)
1-参数为函数: 当DOM加载完成后,执行此回调函数
$(function(){})
2-参数为选择器字符串:查找所有匹配的标签,并将它们封装成jQuery对象
$('div:last')
3-参数为DOM对象:将DOM对象封装成jQuery对象
$(this)
4-参数为HTML标签字符串(很少用):创建标签对象并封装成jQuery对象
$('<p>我是一个p标签</p>')
2.jQuery静态方法,$作为对象使用:$.xxx()
数组静态方法
Array.isArray();
from();
Array.of();
1-$.each() 隐式遍历数组
2-$.trim 取出两端的空格
等等
-->
<script src="./1-jquery.js"></script>
<script>
$(function(){
// var btn=$('button:first');
// btn.click(function(){
// console.log(this,$(this));
// console.log(this.innerHTML);
// console.log($(this).html());
// $('<input type="text">').appendTo('body');
// })
var obj={
name:"zhangsan",
age:12
}
var arr=[1,2,3,4,5]
// 参数:目标对象/数组 回调函数
$.each(arr,function(index,item){
console.log(index,item);
});
var str=' hello world ';
console.log(str);
console.log(str.trim());
console.log($.trim(str));
})
</script>
</head>
<body>
<button>点击我</button>
<input type="text">
<input type="text">
</body>
</html>
2.4 jQuery的核心函数和核心对象
核心函数
简称:jQuery函数($/jQuery)
引入jQuery库以后,直接使用$/jQuery即可
当函数用:$(params)
当对象用的时候:$.each()
核心对象
简称:jQuery对象 $()
得到jQuery对象:执行jQuery函数返回的就是jQuery对象
使用jQuery对象:$obj.xxx()
核心函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./1-jquery.js"></script>
<script>
$(function(){
// var btn=$('button:first');
// btn.click(function(){
// console.log(this,$(this));
// console.log(this.innerHTML);
// console.log($(this).html());
// $('<input type="text">').appendTo('body');
// })
var obj={
name:"zhangsan",
age:12
}
var arr=[1,2,3,4,5]
// 参数:目标对象/数组 回调函数
$.each(arr,function(index,item){
console.log(index,item);
});
var str=' hello world ';
console.log(str);
console.log(str.trim());
console.log($.trim(str));
})
</script>
</head>
<body>
<button>点击我</button>
<input type="text">
<input type="text">
</body>
</html>
核心对象
jQuery对象是类数组对象,jQuery的方法都是对类数组中的元素的批量操作 注意:jQuery对象可以调用jQuery.prototype中声明的方法,普通的Element元素则不能调用。在使用jquery的时候,拿到一个对象务必要搞明白该对象是Element元素还是jQuery实例 如下代码,this是Element元素,如果想调用jQuery方法,需要使用$()将其转换为jQuery实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./1-jquery.js"></script>
<script>
// window.onload=function(){
// var button=document.getElementsByTagName("button")[0];
// var username=document.getElementsByTagName('input')[0];
// button.onclick=function(){
// alert(username.value)
// }
// }
// jquery实例 $() jQuery.prototype
$(function(){
var button=$('button:last');
// jquery绑定事件
button.click(function(){
alert($('input:first').val())
})
})
</script>
</head>
<body>
用户名: <input type="text">
<button>确定(js)</button>
<button>确定(jquery)</button>
</body>
</html>
2.5 jQuery选择器
jQuery的选择器与CSS3中的选择器几乎完全一致,这里就不再赘述。总体梳理:
基本选择器
层次选择器
伪类选择器
伪元素选择器器
属性选择器 具体用法如下:
$("form") $("ul.nav > li")
jQuery中所有选择器都以美元符号开头:$()
例如:
元素选择器
在页面中选取所有<div>
元素
$("div")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./1-jquery.js"></script>
<script>
$(function(){
$('button:first').click(function(){
// $('#one').hide();
// $('.two').hide();
$('#one,.two').hide();
alert($('input[type="text"]').val())
})
})
</script>
</head>
<body>
<button>点击我</button>
<input type="text" value="zhangsan">
<input type="submit" value="">
<input type="email" name="" id="">
<div id="one">我是一个div</div>
<div class="two">我是一个div</div>
<div>我是一个div</div>
<div>我是一个div</div>
</body>
</html>
2.6jQuery事件机制
jQuery的事件绑定与Element元素不同,不可以使用onxxx属性,也不能使用addEventListener,而是使用on(),可以理解为on是对于Element元素事件绑定的封装。 on()也支持事件代理。
-
on(event,[selector],[data],fn)
-
off(event,[selector],fn)
-
one(event,[selector],fn)
-
trigger(event,[data]) jQuery的事件绑定还支持快捷绑定
-
click([data],fn) …
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./1-jquery.js"></script>
<script>
$(function(){
// var btn=$('button:first');
// 绑定事件 on(事件类型,传参(可选),事件处理程序)
// btn.on('click',[1,2,3],function(event){
// console.log(event,'事件对象');
// console.log(event.data);
// $(event.target).html('不想被点');
// });
// // 模拟点击事件
// btn.trigger('click');
// // 解绑事件
// btn.off('click');
// // 绑定事件方法 bind绑定 参数(事件类型,参数(可选),事件处理程序)
// btn.bind('click',[1,2,3],function(e){
// console.log(e,'事件对象');
// });
// btn.unbind();//无参代表全部解绑事件
// // one 绑定事件
// btn.one('click',function(e){
// console.log('我被绑定了',e);
// });
// 事件代理 on(事件类型,代理对象,事件处理程序)
// $('body').on('click','button',function(){
// $('button').html('我被点击了')
// })
// 事件类型
$('button').dblclick(function(){
console.log('我被双击了');
});
$('button').mouseenter(function(){
$(this).css({
backgroundColor:'red'
})
});
$('button').mouseleave(function(){
$(this).css({
backgroundColor:'blue'
})
})
$('input[type="text"]').focus(function(){
$(this).css({
backgroundColor:'red'
})
})
$('input[type="text"]').blur(function(){
$(this).css({
backgroundColor:'blue'
})
})
})
</script>
</head>
<body>
<input type="text">
<button>点击我</button>
<button>点击我</button>
<button>点击我</button>
<button>点击我</button>
<button>点击我</button>
<button>点击我</button>
</body>
</html>
2.7jQueryDOM操作
jQuery中提供了一系列的操作DOM节点的api,用于解决DOM原生API无法进行批量操作并且功能性较差的弊端。 插入方法:append、appendTo、prepend、prependTo、after、before、insertBefore、insertAfter 包裹方法:wrap、unwrap、wrapAll、wrapInner、 替换方法:replaceWith、replaceAll 移除方法:empty、remove、detach 克隆方法:clone
通过 jQuery,可以很容易地添加新元素/内容。
我们将学习用于添加新内容的四个 jQuery 方法:
-
append() - 在被选元素的结尾插入内容(仍然在该元素的内部)
-
prepend() - 在被选元素的开头插入内容
-
after() - 在被选元素之后插入内容
-
before() - 在被选元素之前插入内容
-
等等
复制节点:
原生DOM有 cloneNode(true/false) 浅复制false 深复制true。是否复制内部内容,并不涉及事件的复制。默认浅复制
jQuery对象有 clone(true/false) 浅复制false 深复制true。会复制内容,是否复制事件。默认浅复制
属性操作 在dom中,我们通过setAttribute/getAttribute/style来操作元素属性,jQuery中提供了更加便捷的方法 属性:attr、removeAttr、prop、removeProp css:addClass、removeClass、toggleClass、wrapInner、 内容:html、text、val
jQuery 拥有可操作 HTML 元素和属性的强大方法
三个简单实用的用于 DOM 操作的 jQuery 方法:
-
text() - 设置或返回所选元素的文本内容
-
html() - 设置或返回所选元素的内容(包括 HTML 标记)
-
val() - 设置或返回表单字段的值
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./1-jquery.js"></script> <style> .active{ background-color: red; } .two{ font-size: 28px; } </style> <script> $(function(){ // append插入内容到元素尾部 $('div:first').append('<p>我是一个p标签</p>'); // 创建一个div添加到body尾部 $('<div>我是块级元素</div>').appendTo('body'); // 克隆节点 针对事件 浅克隆不克隆事件 深克隆克隆事件 $('button:first').click(function(){ console.log('我被点击了'); }) // clone方法无参 浅克隆 有参true 深克隆 $('button:first').clone(true).appendTo('body'); // 获取div的id属性值 // attr:参数1 获取该属性名对应的属性值 // 参数:2 给当前dom元素设置/修改属性 console.log($('div:first').attr('id','newId')); // removeAttr 删除属性 $('div:first').removeAttr('title'); // 添加类名 $('div:first').addClass('active'); // 删除类名 删除对应的样式 $('div:first').removeClass('two'); // 切换类名 --对应的是删除或者是添加类名 $('div:first').click(function(){ $(this).toggleClass('active') }); // 获取body标签内部的内容 console.log($('body').html());//innerHTML 识别代码片段 console.log($('body').text());//innerText }) </script> </head> <body> <button>确定</button> <div id="one" class="two" title="我是一个div">我是一个div</div> </body> </html>
2.8jQuery静态方法
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./1-jquery.js"></script> <script> $(function(){ var obj={ name:'zhangsan', age:12 } $.each(obj,function(key,value){ console.log(key,value); }); var arr=[1,2,3]; $.each(arr,function(index,item){ console.log(index,item); }); // map 映射 参数:要操作的数组 回调函数 var res=$.map(arr,function(item,index){ return item+4 }); console.log(res); // toArray 将类数组转成数组--实例方法 console.log($('div').toArray()); // 合并数组 merge console.log($.merge([1,2,3],[4,5,6])); // 将对象转换成查询字符串 var obj={ page:1, pageSize:10 } console.log($.param(obj)); var obj1='{"name":"zhangsan","age":12}'; console.log($.parseJSON(obj1)); }) </script> </head> <body> <div>我是一个div</div> <div>我是一个div</div> <div>我是一个div</div> </body> </html>