执行jquery
执行 jQuery 的方法
jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画和 Ajax 交互。以下是执行 jQuery 的常见方法:
引入 jQuery 库
在 HTML 文件中通过 <script> 标签引入 jQuery 库。可以从 CDN 或本地文件加载:
<!-- 使用 CDN 引入 jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- 或从本地文件引入 -->
<script src="path/to/jquery.min.js"></script>
基本语法
jQuery 的基本语法是 $(selector).action(),其中:
$是 jQuery 的别名。selector用于查找 HTML 元素。action()是对元素执行的操作。
// 示例:隐藏所有 <p> 元素
$("p").hide();
文档就绪事件

确保代码在 DOM 完全加载后执行:
$(document).ready(function() {
// jQuery 代码
});
// 简写形式
$(function() {
// jQuery 代码
});
常见操作示例
- 选择元素
// 选择所有 <div> 元素 $("div");
// 选择 class 为 "example" 的元素 $(".example");

// 选择 id 为 "demo" 的元素 $("#demo");
2. 修改内容
```javascript
// 修改元素文本
$("#demo").text("新文本");
// 修改 HTML 内容
$("#demo").html("<b>新 HTML</b>");
- 事件处理
// 点击事件 $("button").click(function() { alert("按钮被点击"); });
// 鼠标悬停事件 $("#demo").hover(function() { $(this).css("background-color", "yellow"); });
4. CSS 操作
```javascript
// 修改 CSS 属性
$("#demo").css("color", "red");
// 添加/移除 class
$("#demo").addClass("highlight");
$("#demo").removeClass("highlight");
- 动画效果
// 隐藏/显示元素 $("#demo").hide(); $("#demo").show();
// 淡入淡出 $("#demo").fadeIn(); $("#demo").fadeOut();
Ajax 请求
使用 jQuery 发送 Ajax 请求:
```javascript
$.ajax({
url: "example.php",
type: "GET",
data: { name: "John" },
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
注意事项
- 确保 jQuery 库在自定义脚本之前引入。
- 使用开发者工具(如 Chrome DevTools)调试 jQuery 代码。
- 避免与其他库(如 Prototype.js)冲突,可以使用
jQuery.noConflict()。






