jquery的使用
jQuery 的基本使用
jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。以下是 jQuery 的核心使用方法。
引入 jQuery
在 HTML 文件中通过 CDN 引入 jQuery:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
选择器
jQuery 使用 CSS 选择器来选取 DOM 元素:
// 选取所有 <p> 元素
$("p")
// 选取 class 为 "example" 的元素
$(".example")
// 选取 id 为 "demo" 的元素
$("#demo")
DOM 操作
jQuery 提供了简洁的方法操作 DOM:

// 修改元素内容
$("#demo").text("Hello, jQuery!")
// 修改 HTML 内容
$("#demo").html("<strong>Hello</strong>")
// 修改属性
$("img").attr("src", "new-image.jpg")
// 添加或移除 class
$("#demo").addClass("active")
$("#demo").removeClass("inactive")
事件处理
jQuery 简化了事件绑定:
// 点击事件
$("#btn").click(function() {
alert("Button clicked!")
})
// 表单提交事件
$("form").submit(function(e) {
e.preventDefault()
console.log("Form submitted")
})
动画效果
jQuery 内置了简单的动画方法:
// 隐藏和显示
$("#box").hide()
$("#box").show()
// 淡入淡出
$("#box").fadeIn()
$("#box").fadeOut()
// 滑动效果
$("#box").slideUp()
$("#box").slideDown()
Ajax 请求
jQuery 提供了便捷的 Ajax 方法:

// GET 请求
$.get("https://api.example.com/data", function(response) {
console.log(response)
})
// POST 请求
$.post("https://api.example.com/submit", { name: "John" }, function(response) {
console.log(response)
})
链式调用
jQuery 支持链式调用,可以在一行代码中执行多个操作:
$("#demo")
.css("color", "red")
.slideUp(500)
.slideDown(500)
遍历元素
jQuery 提供了遍历 DOM 的方法:
// 遍历每个 <li> 元素
$("li").each(function(index) {
console.log(index + ": " + $(this).text())
})
插件扩展
jQuery 支持通过插件扩展功能,例如引入 jQuery UI 或其他第三方插件:
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
通过以上方法,可以快速上手 jQuery 并实现丰富的交互功能。






