jQuery 基础教程
一、jQuery 简介
1.1 什么是 jQuery
jQuery 是一款轻量级的 JavaScript 库,它诞生于 2006 年,由 John Resig 开发。其核心理念是 “Write Less, Do More”
(写更少的代码,做更多的事情)。它封装了 JavaScript 中繁琐的 DOM 操作、事件处理、动画效果和 AJAX 交互等功能,让开发者能够更高效地完成网页开发工作。
1.2 jQuery 的优势
简化 DOM 操作:无需编写复杂的 JavaScript 代码来获取和操作 DOM 元素,通过简洁的语法即可实现。
跨浏览器兼容性:自动处理不同浏览器之间的差异,开发者无需额外编写兼容性代码,降低开发难度。
丰富的插件生态:拥有大量现成的插件,涵盖表单验证、图片轮播、图表展示等多种功能,可直接引用,提升开发效率。
便捷的事件处理:提供了统一的事件绑定和处理方式,支持事件委托,简化事件管理。
强大的动画效果:内置多种动画函数,如淡入淡出、滑动、显示隐藏等,也支持自定义动画,轻松实现网页动态效果。
二、jQuery 环境搭建
2.1 下载 jQuery 文件
访问 jQuery 官方网站(https://jquery.com/),在首页点击 “Download jQuery” 进入下载页面。
下载页面提供两种版本:
Production version(生产版本):经过压缩,体积小,适合在实际项目中使用。
Development version(开发版本):未压缩,代码可读性高,适合学习和开发调试。
根据需求选择对应版本,点击下载,得到
.js格式的 jQuery 文件。
2.2 引入 jQuery 文件
引入方式有两种,分别是本地引入和 CDN 引入。
2.2.1 本地引入
将下载好的 jQuery 文件放在项目的 js 目录下,在 HTML 文件的 <head> 或 <body> 标签内,通过 <script> 标签引入,示例代码如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>jQuery 本地引入示例</title>
<!-- 本地引入 jQuery 文件 -->
<script src="js/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
// 此处可编写 jQuery 代码
$(document).ready(function () {
alert("jQuery 本地引入成功!");
});
</script>
</body>
</html>2.2.2 CDN 引入
CDN(内容分发网络)引入无需下载 jQuery 文件,直接通过引用第三方提供的 CDN 链接即可使用。常用的 CDN 服务商有百度、新浪、微软等,示例代码如下(以百度
CDN 为例):
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>jQuery CDN 引入示例</title>
<!-- 百度 CDN 引入 jQuery 文件 -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
// 此处可编写 jQuery 代码
$(function () {
alert("jQuery CDN 引入成功!");
});
</script>
</body>
</html>提示:
$(document).ready(function(){})和
$(function(){})是等价的,均表示等待页面 DOM 加载完成后再执行内部代码,避免因 DOM 未加载完成导致无法操作元素的问题。
三、jQuery 选择器
选择器是 jQuery 的核心,用于获取页面中的 DOM 元素。jQuery 选择器语法与 CSS 选择器类似,同时扩展了部分选择器,以下是常用的选择器分类及示例。
3.1 基本选择器
示例代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>基本选择器示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.highlight {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<div id="box">ID 选择器测试</div>
<p class="content">类选择器测试 1</p>
<p class="content">类选择器测试 2</p>
<span>元素选择器测试</span>
<script>
$(function () {
// ID 选择器:将 #box 元素设置为高亮
$("#box").addClass("highlight");
// 类选择器:将所有 .content 元素设置为高亮
$(".content").addClass("highlight");
// 元素选择器:将所有 span 元素设置为高亮
$("span").addClass("highlight");
});
</script>
</body>
</html>3.2 层级选择器
用于根据元素之间的层级关系选择元素,常用语法如下:
3.3 过滤选择器
过滤选择器通过特定的过滤规则筛选元素,以 : 开头,分为基本过滤、内容过滤、可见性过滤等。
3.3.1 基本过滤选择器
示例代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>基本过滤选择器示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.active {
background-color: yellow;
}
</style>
</head>
<body>
<p>第一个 p 标签</p>
<p class="content">第二个 p 标签(带 content 类)</p>
<p>第三个 p 标签</p>
<p>第四个 p 标签</p>
<script>
$(function () {
$("p:first").addClass("active"); // 第一个 p 标签添加黄色背景
$("p:last").addClass("active"); // 最后一个 p 标签添加黄色背景
$("p:eq(1)").addClass("active"); // 索引为 1 的 p 标签添加黄色背景
$("p:not(.content)").css("color", "blue"); // 不带 content 类的 p 标签文字变蓝
});
</script>
</body>
</html>四、jQuery DOM 操作
DOM(文档对象模型)操作是网页开发中的核心需求,jQuery 提供了简洁的方法用于操作 DOM 元素的内容、属性和样式。
4.1 操作元素内容
常用方法有 html()、text() 和 val(),分别用于操作 HTML 内容、文本内容和表单元素值。
示例代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>元素内容操作示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">初始 HTML 内容</div>
<input type="text" id="input" value="初始输入值">
<button id="btn">获取并修改内容</button>
<script>
$(function () {
$("#btn").click(function () {
// 获取内容
let boxHtml = $("#box").html();
let boxText = $("#box").text();
let inputVal = $("#input").val();
alert(`div 的 HTML 内容:${boxHtml}\ndiv 的文本内容:${boxText}\n输入框的值:${inputVal}`);
// 修改内容
$("#box").html("<strong>修改后的 HTML 内容</strong>");
$("#input").val("修改后的输入值");
});
});
</script>
</body>
</html>4.2 操作元素属性
常用方法有 attr()、prop() 和 removeAttr(),用于获取、设置和删除元素属性。
attr():适用于自定义属性和非布尔值属性(如src、href、class等)。获取属性:
$("img").attr("src")设置属性:
$("img").attr("src", "new-img.jpg")设置多个属性:
$("a").attr({href: "``https://www.baidu.com``", target: "_blank"})prop():适用于布尔值属性(如checked、disabled、selected等),推荐操作这类属性时使用prop(),避免出现兼容性问题。获取属性:
$("input[type='checkbox']").prop("checked")(返回 true 或 false)设置属性:
$("input[type='checkbox']").prop("checked", true)removeAttr():删除元素的指定属性,示例:$("img").removeAttr("src")
4.3 操作元素样式
jQuery 提供多种方法操作元素样式,常用的有 css()、addClass()、removeClass() 和 toggleClass()。
css():获取或设置元素的 CSS 样式。获取样式:
$("#box").css("color")设置单个样式:
$("#box").css("color", "red")设置多个样式:
$("#box").css({color: "red", fontSize: "18px", backgroundColor: "#f0f0f0"})addClass(className):为元素添加指定类名(可添加多个类名,用空格分隔),示例:$("#box").addClass("class1 class2")removeClass(className):为元素移除指定类名(不指定类名则移除所有类名),示例:$("#box").removeClass("class1")toggleClass(className):切换元素的类名(元素有该类名则移除,没有则添加),示例:$("#box").toggleClass("active")
五、jQuery 事件处理
事件处理是实现网页交互的关键,jQuery 简化了事件绑定、解绑和触发的过程。
5.1 常用事件绑定方法
5.1.1 直接绑定事件
jQuery 为常用事件(如点击、鼠标移入、表单提交等)提供了直接绑定方法,语法为 $("selector").eventName(callback),常用事件及示例如下:
提示:
e.preventDefault()用于阻止事件的默认行为,如阻止表单默认提交、阻止链接默认跳转等。
5.1.2 on() 方法绑定事件
on() 方法是更灵活的事件绑定方式,支持绑定多个事件、事件委托等,语法如下:
// 绑定单个事件
$("selector").on("eventName", callback);
// 绑定多个事件(同个回调函数)
$("selector").on("event1 event2 event3", callback);
// 绑定多个事件(不同回调函数)
$("selector").on({
event1: callback1,
event2: callback2,
event3: callback3
});示例代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>on() 方法事件绑定示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">点击或鼠标移入我</button>
<script>
$(function () {
$("#btn").on({
click: function () {
alert("按钮被点击了");
},
mouseenter: function () {
$(this).text("鼠标已移入");
},
mouseleave: function () {
$(this).text("点击或鼠标移入我");
}
});
});
</script>
</body>
</html>5.2 事件委托
事件委托是将事件绑定到父元素上,通过事件冒泡机制,处理子元素的事件。适用于动态生成的子元素(动态生成的元素无法直接绑定事件),语法如下:
$("parentSelector").on("eventName", "childSelector", callback);示例代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>事件委托示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="list">
<li>已存在的列表项 1</li>
<li>已存在的列表项 2</li>
</ul>
<button id="addLi">添加新列表项</button>
<script>
$(function () {
// 事件委托:将点击事件绑定到父元素 ul 上,处理子元素 li 的点击
$("#list").on("click", "li", function () {
alert($(this).text());
});
// 动态添加列表项
$("#addLi").click(function () {
$("#list").append("<li>动态添加的列表项</li>");
});
});
</script>
</body>
</html>说明:动态添加的列表项也能触发点击事件,因为事件委托绑定在父元素
ul上,新添加的
li作为子元素,点击事件会冒泡到父元素被处理。
5.3 事件解绑与触发
事件解绑:使用
off()方法解绑通过on()绑定的事件,语法:$("selector").off("eventName")(不指定事件名则解绑所有事件)。事件触发:使用
trigger()方法手动触发绑定的事件,语法:$("selector").trigger("eventName"),示例:$("button").trigger("click")(手动触发按钮的点击事件)。
六、jQuery 动画效果
jQuery 内置了多种动画效果,也支持自定义动画,轻松实现网页动态交互。
6.1 基本显示隐藏动画
show([speed], [callback]):显示隐藏的元素,speed为动画速度(可选,值为slow、fast或毫秒数),callback
为动画完成后的回调函数(可选)。hide([speed], [callback]):隐藏显示的元素,参数同show()。toggle([speed], [callback]):切换元素的显示 / 隐藏状态,参数同show()。
示例代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>基本显示隐藏动画示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
#box {
width: 200px;
height: 200px;
background-color: red;
margin: 20px 0;
}
</style>
</head>
<body>
<button id="showBtn">显示</button>
<button id="hideBtn">隐藏</button>
<button id="toggleBtn">切换</button>
<div id="box"></div>
<script>
$(function () {
$("#showBtn").click(function () {
$("#box").show(1000, function () {
alert("显示动画完成!");
});
});
$("#hideBtn").click(function () {
$("#box").hide("slow");
});
$("#toggleBtn").click(function () {
$("#box").toggle("fast");
});
});
</script>
</body>
</html>6.2 滑动动画
slideDown([speed], [callback]):通过向下滑动显示隐藏的元素。slideUp([speed], [callback]):通过向上滑动隐藏显示的元素。slideToggle([speed], [callback]):切换元素的滑动显示 / 隐藏状态。
6.3 淡入淡出动画
fadeIn([speed], [callback]):通过淡入效果显示隐藏的元素。fadeOut([speed], [callback]):通过淡出效果隐藏显示的元素。fadeToggle([speed], [callback]):切换元素的淡入 / 淡出状态。fadeTo([speed], opacity, [callback]):将元素淡入 / 淡出到指定的透明度(opacity 取值 0~1)。
6.4 自定义动画
使用 animate() 方法实现自定义动画,语法如下:
$("selector").animate(params, [speed], [easing], [callback]);params:必选,对象类型,指定动画的 CSS 属性目标值(如{left: "200px", top: "100px", width: "300px"})。speed:可选,动画速度。easing:可选,动画效果类型(默认swing,即先慢后快再慢;另一种为linear,即匀速)。callback:可选,动画完成后的回调函数。
示例代码(元素移动动画):
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>自定义动画示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
#box {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
left: 0;
top: 50px;
}
</style>
</head>
<body>
<button id="moveBtn">移动元素</button>
<div id="box"></div>
<script>
$(function () {
$("#moveBtn").click(function () {
$("#box").animate({
left: "500px",
top: "200px",
width: "200px",
height: "200px",
borderRadius: "50%" // 变为圆形
}, 2000, "linear", function () {
// 动画完成后,再执行反向动画
$(this).animate({
left: "0",
top: "50px",
width: "100px",
height: "100px",
borderRadius: "0"
}, 2000);
});
});
});
</script>
</body>
</html>七、jQuery AJAX 交互
AJAX(异步 JavaScript 和 XML)用于在不刷新整个页面的情况下,与服务器进行数据交互。jQuery 封装了 AJAX 操作,提供了 $.ajax()、$.get()、$.post() 等方法,简化了异步请求的编写。
7.1 $.get() 方法
用于发送 GET 请求,语法如下:
$.get(url, [data], [success], [dataType]);url:必选,请求的服务器接口地址。data:可选,发送给服务器的参数(对象类型,如{id: 1, name: "test"}),会自动拼接在 URL 后。success(data, status, xhr):可选,请求成功后的回调函数,data为服务器返回的数据,status为请求状态,xhr为
XMLHttpRequest 对象。dataType:可选,服务器返回数据的类型(如json、html、text等),默认自动判断。
示例代码(获取服务器 JSON 数据):
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>$.get() 示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="getDataBtn">获取数据</button>
<div id="result"></div>
<script>
$(function () {
$("#getDataBtn").click(function () {
$.get(
"https://jsonplaceholder.typicode.com/users/1", // 测试接口地址
function (data, status) {
if (status === "success") {
let html = `<p>用户名:${data.name}</p>
<p>邮箱:${data.email}</p>
<p>地址:${data.address.street}, ${data.address.city}</p>`;
$("#result").html(html);
}
},
"json" // 指定返回数据类型为 JSON
);
});
});
</script>
</body>
</html>7.2 $.post() 方法
用于发送 POST 请求,语法与 $.get() 类似,区别在于 POST 请求的参数会放在请求体中,而非 URL 后,更适合传递敏感数据或大量数据,语法如下:
$.post(url, [data], [success], [dataType]);示例代码(向服务器提交数据):
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>$.post() 示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input type="text" id="username" placeholder="请输入用户名">
<button id="submitBtn">提交</button>
<div id="msg"></div>
<script>
$(function () {
$("#submitBtn").click(function () {
let username = $("#username").val().trim();
if (!username) {
alert("请输入用户名!");
return;
}
$.post(
"https://jsonplaceholder.typicode.com/users", // 测试提交接口
{name: username, email: username + "@example.com"}, // 提交的参数
function (data, status) {
if (status === "success") {
$("#msg").html(`提交成功!新用户 ID:${data.id}`).css("color", "green");
}
},
"json"
);
});
});
</script>
</body>
</html>7.3 $.ajax() 方法
$.ajax() 是最灵活的 AJAX 方法,支持自定义请求类型、请求头、超时时间等多种配置,语法如下:
$.ajax({
url: "接口地址",
type: "请求类型(GET/POST 等)",
data: "发送的参数",
dataType: "返回数据类型",
async: true, // 是否异步请求(默认 true,异步)
timeout: 5000, // 超时时间(毫秒)
beforeSend: function (xhr) {
// 请求发送前执行的函数(如添加请求头、显示加载动画等)
console.log("请求即将发送...");
},
success: function (data, status, xhr) {
// 请求成功后的回调函数
},
error: function (xhr, status, error) {
// 请求失败后的回调函数(如网络错误、服务器错误等)
console.log("请求失败:" + error);
},
complete: function (xhr, status) {
// 请求完成后(无论成功或失败)执行的函数
console.log("请求完成...");
}
});示例代码(自定义 AJAX 请求):
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>$.ajax() 示例</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="ajaxBtn">发送 AJAX 请求</button>
<div id="loading" style="display: none;">加载中...</div>
<div id="ajaxResult"></div>
<script>
$(function () {
$("#ajaxBtn").click(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
type: "GET",
dataType: "json",
timeout: 3000,
beforeSend: function () {
// 显示加载动画
$("#loading").show();
},
success: function (data) {
let html = `<h3>${data.title}</h3>
<p>${data.body}</p>`;
$("#ajaxResult").html(html);
},
error: function (xhr, status, error) {
if (status === "timeout") {
$("#ajaxResult").html("请求超时!").css("color", "red");
} else {
$("#ajaxResult").html("请求失败:" + error).css("color", "red");
}
},
complete: function () {
// 隐藏加载动画
$("#loading").hide();
}
});
});
});
</script>
</body>
</html>八、常见问题与注意事项
$ is not defined错误:jQuery 未引入或引入顺序错误(需在自定义代码前引入)。DOM 操作无效:代码未放在入口函数
$(function(){})中,DOM 未加载完成。动态元素事件无效:使用事件委托(绑定到父元素),而非直接绑定。
prop()与attr()混淆:布尔属性(checked/disabled)用prop(),普通属性用attr()。AJAX 跨域问题:需服务器配置 CORS,或使用 JSONP(仅支持 GET 请求)。
动画冲突:同一元素同时执行多个动画时,使用
stop()停止前一个动画:$("#box").stop().animate(...)
九、学习资源
官方文档:https://api.jquery.com/(权威、全面)
菜鸟教程:https://www.runoob.com/jquery/jquery-tutorial.html(适合入门)
插件库:https://jqueryui.com/(官方 UI 插件)、https://plugins.jquery.com/(第三方插件)
评论