jQuery基础学习
1. jQuery介绍
jQuery是一个JavaScript库。是对于ECMAScript、dom、bom的一个简单封装库,让用户操作更加方便,让代码更简洁。
- JQuery安装
在线使用:https://www.bootcdn.cn/jquery/
官网下载:https://jquery.com
中文文档:https://www.jquery123.com
一般我们会选择下载jquery.js 与 jquery.min.js版本,它们的区别在于jquery.min.js是经过压缩的,体积更小,适用于部署环境。而jquery适用于源码研究,我们对于jquery的学习,应该要上升到源码层次。
- jQuery导入方式
本地导入:
将下载好的jquery.js或jquery.min.js包放入项目文件夹下,在head标签中,用script标签src引进,
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>01-HelloWorld.html</title>
<!-- 本地引入 -->
<script src="../../jquery-3.5.1/jquery-3.5.1.js"></script>
</head>
在线引入:
使用在线链接,同样也是在head标签中引入
<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>
</head>
2. JQuery基本语法
2.1 jquery获取dom节点
语法:
通过jQuery和$ 来调用jQuery函数
$(选择器)
$(html片段)
$(Element元素)
$(匿名函数)
2.2 jquery和js入口函数的区别
js入口函数:
window.onload=function(){
}
jquery入口函数:4种方式
<script>
$(document).ready(function(){
alert('我是一个入口函数1')
})
jQuery(document).ready(function(){
alert('我是一个入口函数2')
})
$(function(){
alert('我是一个入口函数3')
})
jQuery(function(){
alert('我是一个入口函数4')
})
</script>
2.3 jquery 选择器
基本选择器: ( " 标签名 " ) 如: ("标签名") 如: ("标签名")如:(“div”)
层次选择器:如 $(“ul.nav > li”)
伪类选择器: 如 $(‘button:first’)
id选择器
类选择器
2.4 jquery DOM操作
jquery中提供了一系列的操作DOM节点的API,用于解决DOM原生代码API无法进行批量操作、功能性较差的弊端
常用方法:
插入节点:append、appendTo、prepend、prependTo
移除:empty、remove
克隆:clone
添加属性:attr、removeAttr、prop、removeProp
添加或移除类名:addClass、removeClass、toggleClass(切换类名)
更改、添加标签内容:html(设置或返回所选元素的内容,包括 HTML 标记)、text(设置或返回所选元素的文本内容)、val(设置或返回表单字段的值)
2.5 事件类型
常用事件:
入口函数:$(document).ready()
点击事件: click()
双击事件:dbclick()
光标悬停:hover()
失去焦点事件:blur()
鼠标进入:mouseenter()
鼠标移出:mouseleave()
键盘按下事件:keydown()
键盘抬起事件:keyup()
2.6 jquery静态方法
静态方法属于定义在jquery函数上的方法。
数组及对象操作的静态方法:
each():遍历对象和数组
// 遍历对象
var obj = {
name: 'zach',
age: 18,
height: '1.88'
}
// 第一个参数 要遍历的数组或对象 第二个参数 处理函数
$.each(obj, function (key, value) {
console.log(key, value);
})
//遍历数组
$.each( [0,1,2], function(index, item){
alert( index + ": " + item);
});
map() 将一个数组中的元素转换到另一个数组中
var arr=$.map( [0,1,2], function(n){
return n + 4;
});
toArray()把jquery集合中所有dom元素恢复成一个数组
console.log($('li').toArray());
merge() 合并两个数组
console.log($.merge(['zhangsan'],[18]))
2.7 字符串操作
param() 将表单数组或者对象序列化
var obj = {
page:1,
pageSize:10
}
console.log($.param(obj));//page=1&pageSize=10
parseJSON() 将JSON字符串转换为js对象/数组
var person='{"name":"Tom","age":18,"school":"middle"}'
console.log(person);
console.log($.parseJSON(person));
trim() 去掉字符串起始和结尾的空格,多用于用户数据的清洗
var str = " hello hello "
console.log(str);
console.log($.trim(str));