jquery使用教程
jQuery 使用教程
引入 jQuery 库
在 HTML 文件中通过 <script> 标签引入 jQuery 库。可以从 CDN 获取最新版本,例如:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
基本语法
jQuery 的核心是通过选择器选取 DOM 元素,并对其进行操作。基本语法为:
$(selector).action()
$是 jQuery 的别名。selector用于选择 HTML 元素。action()是对元素执行的操作。
选择器
jQuery 使用 CSS 选择器语法来选取元素:
// 选取所有 <p> 元素
$("p")
// 选取 id 为 "demo" 的元素
$("#demo")
// 选取 class 为 "test" 的元素
$(".test")
事件处理
jQuery 提供了简洁的事件绑定方法:

// 点击事件
$("button").click(function() {
alert("按钮被点击");
});
// 鼠标悬停事件
$("p").hover(function() {
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "white");
});
DOM 操作
jQuery 简化了 DOM 操作:
// 获取或设置元素内容
$("#demo").text("Hello, jQuery!");
var content = $("#demo").text();
// 添加 HTML 内容
$("#demo").html("<strong>加粗文本</strong>");
// 修改属性
$("img").attr("src", "new-image.jpg");
// 添加类
$("p").addClass("highlight");
// 移除类
$("p").removeClass("highlight");
动画效果
jQuery 内置了多种动画效果:
// 隐藏和显示
$("#demo").hide();
$("#demo").show();
$("#demo").toggle();
// 淡入淡出
$("#demo").fadeIn();
$("#demo").fadeOut();
$("#demo").fadeToggle();
// 滑动效果
$("#demo").slideUp();
$("#demo").slideDown();
$("#demo").slideToggle();
// 自定义动画
$("#demo").animate({
opacity: 0.5,
height: "200px"
}, 1000);
AJAX 请求
jQuery 简化了 AJAX 请求:

// GET 请求
$.get("test.php", function(data) {
$("#result").html(data);
});
// POST 请求
$.post("test.php", { name: "John" }, function(data) {
$("#result").html(data);
});
// 完整的 AJAX 请求
$.ajax({
url: "test.php",
type: "POST",
data: { name: "John" },
success: function(data) {
$("#result").html(data);
},
error: function(xhr, status, error) {
console.error(error);
}
});
链式调用
jQuery 支持链式调用,可以在一行代码中执行多个操作:
$("#demo").css("color", "red").slideUp(1000).slideDown(1000);
插件扩展
jQuery 支持通过插件扩展功能。引入插件后可以直接调用:
<script src="jquery-plugin.js"></script>
<script>
$("#demo").pluginMethod();
</script>
实用工具方法
jQuery 提供了一些实用工具方法:
// 遍历数组
$.each([1, 2, 3], function(index, value) {
console.log(index + ": " + value);
});
// 检查对象类型
$.type("hello"); // 返回 "string"
// 合并对象
var newObj = $.extend({}, obj1, obj2);
注意事项
- 确保在 DOM 完全加载后再执行 jQuery 代码:
$(document).ready(function() {
// jQuery 代码
});
// 简写形式
$(function() {
// jQuery 代码
});
- 避免与其他库冲突,可以使用
noConflict()方法:
var jq = $.noConflict();
jq(document).ready(function() {
jq("button").click(function() {
jq("p").text("jQuery 仍然可用");
});
});






