目录
jQuery 语法解析
jQuery 的核心语法基于 CSS 选择器和链式操作设计,旨在简化 DOM 操作、事件处理和 Ajax 交互。以下是其核心语法结构的详细解析:
基础语法结构
$(selector).action()
- $ 是 jQuery 的别名,等价于
jQuery
,在可能与其他库冲突的情况下可以使用jQuery.noConflict()
来释放$
控制权 - selector 用于选择 HTML 元素,支持:
- CSS1-3 标准选择器(如元素、类、ID、属性、伪类等)
- jQuery 自定义扩展选择器(如
:visible
,:hidden
,:first
等) - 上下文限定(如
$("li", $("#list"))
选择#list
下的所有li
元素)
- action() 是对选中元素执行的方法,可分为:
- 获取方法(如
text()
,val()
不传参时) - 设置方法(如
text("新内容")
,val("输入值")
传参时) - 操作方法(如
hide()
,show()
等)
- 获取方法(如
选择器详解
基本选择器示例
// 元素选择器 - 选择所有 <p> 元素并隐藏
$("p").hide();
// ID 选择器 - 修改 id="demo" 的元素文字颜色为红色
$("#demo").css("color", "red");
// 类选择器 - 淡出所有 class="item" 的元素
$(".item").fadeOut();
// 属性选择器 - 选择所有 href 属性以 "https" 开头的 <a> 元素
$("a[href^='https']").addClass("external-link");
// 复合选择器 - 选择 class="active" 的直接子 <li> 元素
$("ul > li.active").css("font-weight", "bold");
层次选择器
// 后代选择器 - 选择 #nav 下的所有 <a> 元素
$("#nav a").addClass("nav-link");
// 子元素选择器 - 只选择 #menu 的直接子 <li> 元素
$("#menu > li").addClass("top-level");
// 相邻兄弟选择器 - 选择紧接在 h2 后的第一个 <p> 元素
$("h2 + p").css("margin-top", "0");
// 通用兄弟选择器 - 选择 h2 之后的所有同级 <p> 元素
$("h2 ~ p").addClass("section-content");
过滤选择器
// 基本过滤
$("tr:even").addClass("striped"); // 选择偶数行
$("input:checked").prop("disabled", true); // 选择所有选中的复选框
// 内容过滤
$("td:empty").text("暂无数据"); // 选择空单元格
$("p:contains('jQuery')").addClass("has-keyword"); // 选择包含特定文本的元素
// 可见性过滤
$("div:hidden").show(); // 显示所有隐藏的 div
$("img:visible").fadeOut(1000); // 淡出所有可见图片
文档就绪事件
确保代码在 DOM 完全加载后执行:
// 完整写法
$(document).ready(function() {
// 这里写 jQuery 代码
console.log("DOM 已完全加载");
});
// 简写形式(推荐)
$(function() {
// 代码
$("#loader").hide();
});
// 多 ready 事件会按顺序执行
$(function() {
console.log("第一个 ready 事件");
});
$(function() {
console.log("第二个 ready 事件");
});
链式调用详解
jQuery 方法通常会返回 jQuery 对象,支持链式操作:
// 典型链式调用示例
$("#notification")
.addClass("alert") // 添加类
.css("opacity", 0) // 设置初始透明度
.slideDown(300) // 向下滑动显示
.delay(2000) // 停留2秒
.fadeOut(500) // 淡出
.queue(function(next) { // 使用队列
$(this).removeClass("alert");
next();
});
// 链式调用的中断与恢复
var $items = $(".list-item")
.hide() // 先隐藏
.filter(":odd") // 筛选奇数项
.show() // 显示筛选结果
.end() // 返回初始集合
.css("color", "blue"); // 为所有项设置颜色
常用方法分类
DOM 操作方法
// 内容操作
$("#content").html("<p>新内容</p>"); // 设置HTML
var text = $("h1").text(); // 获取文本内容
// 元素操作
$("<div>").addClass("box").appendTo("body"); // 创建并添加元素
$(".old-item").remove(); // 删除元素
// 属性操作
$("img").attr("alt", "描述文字"); // 设置属性
var src = $("img").prop("src"); // 获取属性
CSS 处理方法
// 类操作
$("button").addClass("btn-primary"); // 添加类
$("#menu").toggleClass("collapsed"); // 切换类
// 样式操作
$(".box").css("width", "200px"); // 设置单个样式
$(".panel").css({ // 设置多个样式
"background-color": "#f5f5f5",
"border": "1px solid #ddd",
"padding": "15px"
});
事件处理方法
// 事件绑定
$("#btn-submit").on("click", function() {
alert("表单已提交");
});
// 快捷方法
$("#gallery img").hover(
function() { $(this).stop().fadeTo(200, 0.7); }, // mouseenter
function() { $(this).stop().fadeTo(200, 1); } // mouseleave
);
// 事件委托
$("#dynamic-list").on("click", ".item", function() {
$(this).toggleClass("selected");
});
动画效果方法
// 基础显示/隐藏
$("#message").fadeIn(500).delay(2000).fadeOut(500);
// 自定义动画
$(".progress-bar").animate({
width: "75%",
opacity: 0.8
}, 1000, "linear", function() {
console.log("动画完成");
});
// 动画队列控制
$("#box")
.slideUp(300)
.slideDown(300)
.queue(function(next) {
$(this).css("background", "yellow");
next();
});
Ajax 请求方法
// $.ajax 完整配置
$.ajax({
url: "api/data",
method: "POST",
data: { id: 123 },
dataType: "json",
success: function(response) {
console.log("请求成功", response);
},
error: function(xhr, status, error) {
console.error("请求失败", status, error);
}
});
// 快捷方法
$.get("data.json", function(data) {
console.log("Received:", data);
});
$.post("/submit", $("#form").serialize(), function(res) {
alert(res.message);
});
// 加载HTML片段
$("#content").load("partials/about.html #main-section");
特殊语法技巧
方法参数灵活传递
// CSS 多属性设置
$("div.container").css({
"margin": "20px auto",
"padding": "15px",
"border-radius": "5px"
});
// attr 多属性设置
$("img.thumbnail").attr({
"title": "点击查看大图",
"data-zoomable": "true"
});
// 回调函数动态设置值
$("input").val(function(index, oldValue) {
return oldValue + " (已校验)";
});
延迟与队列控制
// 延迟执行
$("#banner")
.delay(2000) // 延迟2秒
.fadeIn(500)
.delay(3000)
.fadeOut(500);
// 自定义队列
$("#box")
.queue("custom", function(next) {
$(this).css("color", "red");
next();
})
.dequeue("custom");
扩展与插件开发
// 方法扩展
$.fn.highlight = function(color) {
return this.css("background-color", color || "#ffff99");
};
$("p.important").highlight();
// 工具方法扩展
$.greet = function(name) {
return "Hello, " + name;
};
console.log($.greet("World"));
性能优化建议
-
选择器优化:
- 尽量使用 ID 选择器 (
$("#id")
) 最快 - 避免过度具体的选择器 (
$("div.container ul li a")
) - 缓存 jQuery 对象:
var $nav = $("#navigation");
- 尽量使用 ID 选择器 (
-
DOM 操作优化:
- 批量操作:先分离操作再插入文档
var $list = $("#list").detach(); // 大量操作... $list.appendTo("body");
- 使用文档片段:
var fragment = document.createDocumentFragment(); for(var i=0; i<100; i++) { $(fragment).append("<div>"+i+"</div>"); } $("#container").append(fragment);
-
事件委托:
// 差:为每个元素绑定事件 $("table tr").on("click", function() { ... }); // 好:使用事件委托 $("table").on("click", "tr", function() { ... });
-
动画优化:
- 使用
stop()
防止动画队列堆积
$("#menu").stop(true, true).slideToggle();
- 对
position: absolute/fixed
元素做动画性能更好
- 使用
jQuery 3.x 在保持 API 兼容性的同时,移除了过时的方法,改进了 Promise/A+ 支持,并优化了性能。对于新项目,建议评估是否真的需要 jQuery,但维护旧代码时仍需深入掌握其语法规则。