一、jQuery 基礎
-
核心概念
-
$
?或?jQuery
:全局函數,用于選擇元素或創建DOM對象。 -
鏈式調用:多數方法返回jQuery對象,支持連續操作。
-
文檔就緒事件:
$(document).ready(function() { /* 代碼 */ }); // 簡寫 $(function() { /* 代碼 */ });
-
-
選擇器
-
基礎選擇器:
-
$("#id")
、$(".class")
、$("tag")
、$("*")
(通配符)。
-
-
層級選擇器:
-
$("parent > child")
(子元素)、$("ancestor descendant")
(后代)。
-
-
過濾選擇器:
-
:first
、:last
、:even
、:odd
、:eq(index)
、:not(selector)
。
-
-
屬性選擇器:
-
$("[attr]")
、$("[attr='value']")
。
-
-
-
DOM 遍歷
-
向上查找:
parent()
、parents()
、closest(selector)
。 -
同級查找:
siblings()
、next()
、prev()
、nextAll()
。 -
向下查找:
children()
、find(selector)
。
-
二、DOM 操作
-
內容操作
-
獲取/設置文本:
text()
、text("new text")
。 -
獲取/設置HTML:
html()
、html("<b>new html</b>")
。 -
表單值:
val()
、val("new value")
。
-
-
屬性與CSS
-
屬性操作:
-
attr("name")
、attr("name", "value")
。 -
removeAttr("name")
。
-
-
CSS操作:
-
css("property")
、css("property", "value")
。 -
添加/移除類:
addClass()
、removeClass()
、toggleClass()
。
-
-
-
節點操作
-
創建元素:
$("<div>New Element</div>")
。 -
插入元素:
-
append()
、prepend()
(內部插入)。 -
after()
、before()
(外部插入)。
-
-
刪除元素:
remove()
、empty()
。
-
三、事件處理
-
事件綁定
-
簡寫方法:
click()
、hover()
、submit()
。 -
通用方法:
on("event", handler)
(推薦統一使用)。$("#btn").on("click", function() { alert("Clicked!"); });
-
事件解綁:
off("event")
。
-
-
事件委托
-
動態元素事件綁定:
$("#parent").on("click", ".child", function() { /* 邏輯 */ });
-
-
常用事件
-
鼠標事件:
click
、dblclick
、mouseenter
、mouseleave
。 -
鍵盤事件:
keypress
、keyup
、keydown
。 -
表單事件:
submit
、change
、focus
、blur
。
-
四、動畫與效果
-
基礎動畫
-
顯示/隱藏:
show()
、hide()
、toggle()
。 -
淡入淡出:
fadeIn()
、fadeOut()
、fadeToggle()
。 -
滑動效果:
slideDown()
、slideUp()
、slideToggle()
。
-
-
自定義動畫
-
animate()
?方法:$("#box").animate({ opacity: 0.5, left: "+=50px" }, 1000);
-
停止動畫:
stop()
、delay()
。
-
五、AJAX 與工具方法
-
AJAX 請求
-
$.ajax()
(底層方法):$.ajax({url: "api/data",method: "GET",success: function(data) { console.log(data); } });
-
簡寫方法:
-
$.get(url, callback)
、$.post(url, data, callback)
。 -
$.getJSON(url, callback)
。
-
-
-
工具函數
-
數組/對象操作:
-
$.each(array, function(index, value) {})
。 -
$.extend()
(合并對象)。
-
-
類型判斷:
-
$.isArray()
、$.isFunction()
。
-
-
六、插件與擴展
-
使用插件
-
引入jQuery插件(如?
jQuery UI
、DataTables
):<script src="jquery.plugin.js"></script>
-
-
編寫插件
-
擴展jQuery方法:
(function($) {$.fn.myPlugin = function(options) {// 插件邏輯}; })(jQuery);
-
七、性能優化
-
選擇器優化
-
緩存jQuery對象:
var $el = $("#element");
。 -
避免過度嵌套選擇器(如?
$("div ul li a")
)。
-
-
事件優化
-
使用事件委托代替重復綁定。
-
移除無用事件監聽(
off()
)。
-
-
鏈式調用
-
減少DOM查詢次數:
$("#box").css("color", "red").slideDown().fadeIn();
-
八、兼容性與現代替代
-
jQuery 與原生JS
-
對比示例:
-
$("#id")
?→?document.getElementById("id")
。 -
$.ajax
?→?fetch
?API。
-
-
-
現代替代方案
-
原生JS +?
querySelector
。 -
前端框架(React/Vue)的組件化開發。
-
學習建議
-
快速上手:從DOM操作和事件處理開始實踐。
-
官方文檔:jQuery API。
-
逐步過渡:理解jQuery原理后,轉向現代JS或框架。
jQuery的核心優勢是簡化DOM操作和跨瀏覽器兼容性,適合快速開發傳統Web應用,但在現代開發中可結合需求選擇是否使用。