简体中文 繁體中文 English 日本語 Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français

站内搜索

搜索

活动公告

11-02 12:46
10-23 09:32
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31
10-23 09:28
通知:签到时间调整为每日4:00(东八区)
10-23 09:26

jQuery 1.11 完整手册 开发者必备资源 全面覆盖API参考 实例教程 常见问题解答 从入门到精通 助力高效开发 解决实际项目问题

3万

主题

423

科技点

3万

积分

大区版主

木柜子打湿

积分
31916

三倍冰淇淋无人之境【一阶】财Doro小樱(小丑装)立华奏以外的星空【二阶】⑨的冰沙

发表于 2025-10-6 12:40:29 | 显示全部楼层 |阅读模式 [标记阅至此楼]

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
1. jQuery简介与1.11版本概述

jQuery是一个快速、小型且功能丰富的JavaScript库。它使HTML文档遍历和操作、事件处理、动画和Ajax等事情变得更加简单,具有易于使用的API,可在多种浏览器上工作。jQuery 1.11版本是1.x系列中的一个重要版本,它专注于兼容性和稳定性,特别适合需要支持旧版浏览器的项目。

1.1 jQuery的优势

• 跨浏览器兼容性:jQuery处理了不同浏览器之间的差异,使开发者不必担心兼容性问题
• 简洁的语法:jQuery提供了简洁易用的API,可以用更少的代码完成更多的工作
• 丰富的插件生态系统:有大量可用的插件,扩展了jQuery的功能
• 强大的功能集:包括DOM操作、事件处理、动画效果和AJAX等功能

1.2 jQuery 1.11版本特点

jQuery 1.11版本发布于2014年,具有以下特点:

• 继续支持IE 6/7/8等旧版浏览器
• 修复了1.10版本中的一些bug
• 性能优化和内存泄漏修复
• 与jQuery 2.x系列并行开发,但保持对旧浏览器的支持

1.3 引入jQuery

在HTML文档中引入jQuery 1.11有两种方式:

方式一:使用CDN
  1. <!-- 从jQuery CDN引入 -->
  2. <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
  3. <!-- 或者使用Google CDN -->
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  5. <!-- 或者使用Microsoft CDN -->
  6. <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.11.3.min.js"></script>
复制代码

方式二:下载本地文件
  1. <!-- 下载到本地后引入 -->
  2. <script src="js/jquery-1.11.3.min.js"></script>
复制代码

2. jQuery基础

2.1 jQuery语法基础

jQuery语法是为HTML元素的选取和操作而特别设计的。基本语法是$(selector).action():

• $:定义jQuery
• selector:查询和查找HTML元素
• action():执行对元素的操作

文档就绪处理

为了防止文档在完全加载(就绪)之前运行jQuery代码,所有的jQuery函数都应放在文档就绪处理函数中:
  1. $(document).ready(function(){
  2.    // jQuery代码写在这里
  3. });
  4. // 简写形式
  5. $(function(){
  6.    // jQuery代码写在这里
  7. });
复制代码

2.2 jQuery选择器

jQuery选择器允许您对HTML元素组或单个元素进行操作。jQuery选择器基于元素的id、类、类型、属性、属性值等”查找”(或选择)HTML元素。
  1. // 元素选择器
  2. $("p")         // 选取所有<p>元素
  3. // ID选择器
  4. $("#test")     // 选取id="test"的元素
  5. // 类选择器
  6. $(".test")     // 选取所有class="test"的元素
  7. // 全局选择器
  8. $("*")         // 选取所有元素
  9. // 多元素选择器
  10. $("p.intro")   // 选取所有class="intro"的<p>元素
  11. $("p#demo")    // 选取所有id="demo"的<p>元素
复制代码
  1. // 后代选择器
  2. $("div p")     // 选取<div>元素内的所有<p>元素
  3. // 子选择器
  4. $("div > p")   // 选取<div>元素的所有直接子元素<p>
  5. // 相邻兄弟选择器
  6. $("div + p")   // 选取<div>元素之后的下一个<p>元素
  7. // 一般兄弟选择器
  8. $("div ~ p")   // 选取<div>元素之后的所有兄弟<p>元素
复制代码
  1. // :first选择器
  2. $("p:first")   // 选取第一个<p>元素
  3. // :last选择器
  4. $("p:last")    // 选取最后一个<p>元素
  5. // :even选择器
  6. $("tr:even")   // 选取所有偶数位置的<tr>元素
  7. // :odd选择器
  8. $("tr:odd")    // 选取所有奇数位置的<tr>元素
  9. // :eq(index)选择器
  10. $("ul li:eq(3)") // 选取列表中的第四个元素(index从0开始)
  11. // :gt(index)选择器
  12. $("ul li:gt(3)") // 选取列表中index大于3的元素
  13. // :lt(index)选择器
  14. $("ul li:lt(3)") // 选取列表中index小于3的元素
  15. // :not(selector)选择器
  16. $("input:not(:empty)") // 选取所有不为空的input元素
复制代码
  1. // [attribute]选择器
  2. $("[href]")      // 选取所有带有href属性的元素
  3. // [attribute=value]选择器
  4. $("[href='#']")  // 选取所有带有href属性且值等于"#"的元素
  5. // [attribute!=value]选择器
  6. $("[href!='#']") // 选取所有带有href属性且值不等于"#"的元素
  7. // [attribute$=value]选择器
  8. $("[href$='.jpg']") // 选取所有href属性值以".jpg"结尾的元素
  9. // [attribute^=value]选择器
  10. $("[href^='https']") // 选取所有href属性值以"https"开头的元素
  11. // [attribute*=value]选择器
  12. $("[href*='jquery']") // 选取所有href属性值包含"jquery"的元素
复制代码
  1. // :input选择器
  2. $(":input")     // 选取所有<input>, <textarea>, <select>和<button>元素
  3. // :text选择器
  4. $(":text")      // 选取所有type="text"的<input>元素
  5. // :password选择器
  6. $(":password")  // 选取所有type="password"的<input>元素
  7. // :radio选择器
  8. $(":radio")     // 选取所有type="radio"的<input>元素
  9. // :checkbox选择器
  10. $(":checkbox")  // 选取所有type="checkbox"的<input>元素
  11. // :submit选择器
  12. $(":submit")    // 选取所有type="submit"的<input>元素
  13. // :reset选择器
  14. $(":reset")     // 选取所有type="reset"的<input>元素
  15. // :button选择器
  16. $(":button")    // 选取所有type="button"的<input>元素和<button>元素
  17. // :image选择器
  18. $(":image")     // 选取所有type="image"的<input>元素
  19. // :file选择器
  20. $(":file")      // 选取所有type="file"的<input>元素
  21. // :enabled选择器
  22. $(":enabled")   // 选取所有启用的表单元素
  23. // :disabled选择器
  24. $(":disabled")  // 选取所有禁用的表单元素
  25. // :selected选择器
  26. $(":selected")  // 选取所有被选中的<option>元素
  27. // :checked选择器
  28. $(":checked")   // 选取所有被选中的复选框和单选按钮
复制代码

2.3 jQuery事件处理

jQuery事件处理方法是jQuery中的核心功能之一。事件处理程序指的是当HTML中发生某些事件时所调用的方法。
  1. // click()方法
  2. $("p").click(function(){
  3.     $(this).hide();
  4. });
  5. // dblclick()方法
  6. $("p").dblclick(function(){
  7.     $(this).hide();
  8. });
  9. // mouseenter()方法
  10. $("#p1").mouseenter(function(){
  11.     alert("您进入了 p1!");
  12. });
  13. // mouseleave()方法
  14. $("#p1").mouseleave(function(){
  15.     alert("再见,您离开了 p1!");
  16. });
  17. // mousedown()方法
  18. $("#p1").mousedown(function(){
  19.     alert("鼠标在该段落上按下!");
  20. });
  21. // mouseup()方法
  22. $("#p1").mouseup(function(){
  23.     alert("鼠标在段落上松开!");
  24. });
  25. // hover()方法
  26. $("#p1").hover(
  27.     function(){
  28.         alert("你进入了 p1!");
  29.     },
  30.     function(){
  31.         alert("再见,你现在离开了 p1!");
  32.     }
  33. );
  34. // focus()方法
  35. $("input").focus(function(){
  36.     $(this).css("background-color","#cccccc");
  37. });
  38. // blur()方法
  39. $("input").blur(function(){
  40.     $(this).css("background-color","#ffffff");
  41. });
复制代码

on()方法是jQuery 1.7版本引入的,用于绑定事件处理程序,提供了比bind()、live()和delegate()方法更灵活的功能。
  1. // 基本用法
  2. $("p").on("click", function(){
  3.     $(this).hide();
  4. });
  5. // 绑定多个事件
  6. $("p").on({
  7.     mouseenter: function(){
  8.         $(this).css("background-color", "lightgray");
  9.     },
  10.     mouseleave: function(){
  11.         $(this).css("background-color", "white");
  12.     },
  13.     click: function(){
  14.         $(this).css("background-color", "yellow");
  15.     }
  16. });
  17. // 事件委托
  18. $(document).on("click", "p", function(){
  19.     $(this).hide();
  20. });
复制代码

当事件被触发时,事件对象(event object)会被传递给事件处理函数:
  1. $("p").click(function(event){
  2.     // 阻止默认行为
  3.     event.preventDefault();
  4.    
  5.     // 阻止事件冒泡
  6.     event.stopPropagation();
  7.    
  8.     // 获取事件类型
  9.     alert(event.type); // "click"
  10.    
  11.     // 获取触发事件的元素
  12.     alert(event.target);
  13.    
  14.     // 获取页面X坐标
  15.     alert(event.pageX);
  16.    
  17.     // 获取页面Y坐标
  18.     alert(event.pageY);
  19. });
复制代码

jQuery允许你创建自定义事件:
  1. // 绑定自定义事件
  2. $("p").on("myCustomEvent", function(event, myName, myValue){
  3.     $(this).text(myName + ", 你好! " + myValue);
  4. });
  5. // 触发自定义事件
  6. $("button").click(function(){
  7.     $("p").trigger("myCustomEvent", ["John", "工程师"]);
  8. });
复制代码

2.4 jQuery DOM操作

jQuery提供了多种方法来操作DOM元素,包括获取和设置内容、属性、样式等。
  1. // text() - 设置或返回所选元素的文本内容
  2. $("#test").text(); // 获取文本内容
  3. $("#test").text("Hello world!"); // 设置文本内容
  4. // html() - 设置或返回所选元素的内容(包括HTML标记)
  5. $("#test").html(); // 获取内容
  6. $("#test").html("<b>Hello world!</b>"); // 设置内容
  7. // val() - 设置或返回表单字段的值
  8. $("#test").val(); // 获取值
  9. $("#test").val("John Doe"); // 设置值
复制代码
  1. // attr() - 设置或返回属性值
  2. $("#w3s").attr("href"); // 获取href属性值
  3. $("#w3s").attr("href", "https://www.w3schools.com/jquery/"); // 设置href属性值
  4. // 同时设置多个属性
  5. $("#w3s").attr({
  6.     "href" : "https://www.w3schools.com/jquery/",
  7.     "title" : "jQuery Tutorial"
  8. });
  9. // prop() - 设置或返回属性值(适用于checked、selected、disabled等属性)
  10. $("#checkbox1").prop("checked"); // 获取checked属性
  11. $("#checkbox1").prop("checked", true); // 设置checked属性
  12. // removeAttr() - 移除属性
  13. $("#w3s").removeAttr("title");
复制代码
  1. // append() - 在被选元素的结尾插入内容
  2. $("p").append("Some appended text.");
  3. // prepend() - 在被选元素的开头插入内容
  4. $("p").prepend("Some prepended text.");
  5. // after() - 在被选元素之后插入内容
  6. $("img").after("Some text after");
  7. // before() - 在被选元素之前插入内容
  8. $("img").before("Some text before");
复制代码
  1. // remove() - 删除被选元素(及其子元素)
  2. $("#div1").remove();
  3. // empty() - 从被选元素中删除子元素
  4. $("#div1").empty();
  5. // remove()方法可接受一个参数,允许您对被删元素进行过滤
  6. $("p").remove(".italic"); // 删除所有class="italic"的<p>元素
复制代码
  1. // addClass() - 向被选元素添加一个或多个类
  2. $("h1, h2, p").addClass("blue");
  3. $("div").addClass("important blue");
  4. // removeClass() - 从被选元素删除一个或多个类
  5. $("h1, h2, p").removeClass("blue");
  6. // toggleClass() - 对被选元素进行添加/删除类的切换操作
  7. $("h1, h2, p").toggleClass("blue");
  8. // hasClass() - 检查被选元素是否包含指定的类
  9. $("h1").hasClass("blue"); // 返回true或false
复制代码
  1. // css() - 设置或返回样式属性
  2. $("p").css("background-color"); // 返回背景颜色
  3. $("p").css("background-color", "yellow"); // 设置背景颜色
  4. // 设置多个CSS属性
  5. $("p").css({
  6.     "background-color": "yellow",
  7.     "font-size": "200%"
  8. });
  9. // 尺寸相关方法
  10. // width()和height()方法
  11. $("#div1").width(); // 返回宽度
  12. $("#div1").width(500); // 设置宽度
  13. $("#div1").height(); // 返回高度
  14. $("#div1").height(500); // 设置高度
  15. // innerWidth()和innerHeight()方法
  16. $("#div1").innerWidth(); // 返回宽度(包括内边距)
  17. $("#div1").innerHeight(); // 返回高度(包括内边距)
  18. // outerWidth()和outerHeight()方法
  19. $("#div1").outerWidth(); // 返回宽度(包括内边距和边框)
  20. $("#div1").outerHeight(); // 返回高度(包括内边距和边框)
  21. $("#div1").outerWidth(true); // 返回宽度(包括内边距、边框和外边距)
  22. $("#div1").outerHeight(true); // 返回高度(包括内边距、边框和外边距)
复制代码
  1. // parent() - 返回被选元素的直接父元素
  2. $("span").parent();
  3. // parents() - 返回被选元素的所有祖先元素
  4. $("span").parents();
  5. // parentsUntil() - 返回介于两个给定元素之间的所有祖先元素
  6. $("span").parentsUntil("div");
  7. // children() - 返回被选元素的所有直接子元素
  8. $("div").children();
  9. // find() - 返回被选元素的后代元素
  10. $("div").find("span");
  11. // siblings() - 返回被选元素的所有同胞元素
  12. $("h2").siblings();
  13. // next() - 返回被选元素的下一个同胞元素
  14. $("h2").next();
  15. // nextAll() - 返回被选元素的所有跟随的同胞元素
  16. $("h2").nextAll();
  17. // nextUntil() - 返回介于两个给定参数之间的所有跟随的同胞元素
  18. $("h2").nextUntil("h6");
  19. // prev(), prevAll()和prevUntil()方法的工作方式与上面的方法类似,只不过方向相反
  20. // first() - 返回被选元素的首个元素
  21. $("div p").first();
  22. // last() - 返回被选元素的最后一个元素
  23. $("div p").last();
  24. // eq() - 返回被选元素中带有指定索引号的元素
  25. $("p").eq(1);
  26. // filter() - 允许您规定一个标准。不匹配这个标准的元素会被从集合中删除,匹配的元素会被返回
  27. $("p").filter(".intro");
  28. // not() - 返回不匹配标准的所有元素
  29. $("p").not(".intro");
复制代码

3. jQuery高级特性

3.1 jQuery AJAX

AJAX是与服务器交换数据的技术,它在不重载全部页面的情况下,实现了对部分网页的更新。
  1. // load()方法 - 从服务器加载数据,并把返回的数据放入被选元素中
  2. $("#div1").load("demo_test.txt"); // 加载文件内容
  3. $("#div1").load("demo_test.txt #p1"); // 加载文件中id="p1"的元素
  4. // $.get()方法 - 通过HTTP GET请求从服务器上请求数据
  5. $.get("demo_test.php", function(data, status){
  6.     alert("数据: " + data + "\n状态: " + status);
  7. });
  8. // $.post()方法 - 通过HTTP POST请求从服务器上请求数据
  9. $.post("demo_test_post.php",
  10.     {
  11.         name: "John",
  12.         city: "Boston"
  13.     },
  14.     function(data, status){
  15.         alert("数据: " + data + "\n状态: " + status);
  16.     }
  17. );
  18. // $.ajax()方法 - 执行异步HTTP(Ajax)请求
  19. $.ajax({
  20.     url: "test.html",
  21.     context: document.body,
  22.     success: function(){
  23.         $(this).addClass("done");
  24.     }
  25. });
  26. // 更复杂的$.ajax()示例
  27. $.ajax({
  28.     type: "POST",
  29.     url: "some.php",
  30.     data: { name: "John", location: "Boston" },
  31.     dataType: "json",
  32.     success: function(data){
  33.         // 处理返回的数据
  34.     },
  35.     error: function(xhr, status, error){
  36.         // 处理错误
  37.     },
  38.     complete: function(xhr, status){
  39.         // 请求完成后调用的函数
  40.     }
  41. });
复制代码

jQuery提供了一组用于AJAX事件的全局事件处理程序:
  1. // ajaxStart() - 在AJAX请求开始前执行
  2. $(document).ajaxStart(function(){
  3.     $(this).html("<img src='demo_wait.gif' />");
  4. });
  5. // ajaxSend() - 在AJAX请求发送前执行
  6. $(document).ajaxSend(function(event, xhr, options){
  7.     $(this).html("正在发送请求...");
  8. });
  9. // ajaxSuccess() - 在AJAX请求成功时执行
  10. $(document).ajaxSuccess(function(event, xhr, options){
  11.     $(this).html("请求成功!");
  12. });
  13. // ajaxError() - 在AJAX请求失败时执行
  14. $(document).ajaxError(function(event, xhr, options, exc){
  15.     $(this).html("请求出错:" + xhr.statusText);
  16. });
  17. // ajaxComplete() - 在AJAX请求完成时执行(无论成功或失败)
  18. $(document).ajaxComplete(function(event, xhr, options){
  19.     $(this).html("请求完成");
  20. });
  21. // ajaxStop() - 在所有AJAX请求完成后执行
  22. $(document).ajaxStop(function(){
  23.     $(this).html("所有请求完成");
  24. });
复制代码

3.2 jQuery动画

jQuery提供了一组用于创建自定义动画的函数。
  1. // hide()和show()方法
  2. $("#hide").click(function(){
  3.     $("p").hide();
  4. });
  5. $("#show").click(function(){
  6.     $("p").show();
  7. });
  8. // toggle()方法
  9. $("button").click(function(){
  10.     $("p").toggle();
  11. });
  12. // 可以使用speed参数控制速度
  13. $("button").click(function(){
  14.     $("p").toggle(1000); // 1000毫秒
  15. });
  16. // 可以使用callback参数在动画完成后执行函数
  17. $("button").click(function(){
  18.     $("p").toggle(1000, function(){
  19.         alert("动画完成");
  20.     });
  21. });
复制代码
  1. // fadeIn()方法
  2. $("button").click(function(){
  3.     $("#div1").fadeIn();
  4.     $("#div2").fadeIn("slow");
  5.     $("#div3").fadeIn(3000);
  6. });
  7. // fadeOut()方法
  8. $("button").click(function(){
  9.     $("#div1").fadeOut();
  10.     $("#div2").fadeOut("slow");
  11.     $("#div3").fadeOut(3000);
  12. });
  13. // fadeToggle()方法
  14. $("button").click(function(){
  15.     $("#div1").fadeToggle();
  16.     $("#div2").fadeToggle("slow");
  17.     $("#div3").fadeToggle(3000);
  18. });
  19. // fadeTo()方法 - 允许渐变为给定的不透明度(值介于0与1之间)
  20. $("button").click(function(){
  21.     $("#div1").fadeTo("slow", 0.15);
  22.     $("#div2").fadeTo("slow", 0.4);
  23.     $("#div3").fadeTo("slow", 0.7);
  24. });
复制代码
  1. // slideDown()方法
  2. $("#flip").click(function(){
  3.     $("#panel").slideDown();
  4. });
  5. // slideUp()方法
  6. $("#flip").click(function(){
  7.     $("#panel").slideUp();
  8. });
  9. // slideToggle()方法
  10. $("#flip").click(function(){
  11.     $("#panel").slideToggle();
  12. });
复制代码
  1. // animate()方法 - 创建自定义动画
  2. $("button").click(function(){
  3.     $("div").animate({left: '250px'});
  4. });
  5. // 操作多个属性
  6. $("button").click(function(){
  7.     $("div").animate({
  8.         left: '250px',
  9.         opacity: '0.5',
  10.         height: '150px',
  11.         width: '150px'
  12.     });
  13. });
  14. // 使用相对值
  15. $("button").click(function(){
  16.     $("div").animate({
  17.         left: '250px',
  18.         height: '+=150px',
  19.         width: '+=150px'
  20.     });
  21. });
  22. // 使用预定义的值
  23. $("button").click(function(){
  24.     $("div").animate({
  25.         height: 'toggle'
  26.     });
  27. });
  28. // 使用队列功能
  29. $("button").click(function(){
  30.     var div = $("div");
  31.     div.animate({height: '300px', opacity: '0.4'}, "slow");
  32.     div.animate({width: '300px', opacity: '0.8'}, "slow");
  33.     div.animate({height: '100px', opacity: '0.4'}, "slow");
  34.     div.animate({width: '100px', opacity: '0.8'}, "slow");
  35. });
  36. // 停止动画
  37. $("#stop").click(function(){
  38.     $("#panel").stop();
  39. });
复制代码

3.3 jQuery插件开发

jQuery插件是扩展jQuery功能的一种方式,可以让您创建可重用的代码。
  1. // 创建一个简单的插件
  2. (function($) {
  3.     $.fn.greenify = function() {
  4.         this.css("color", "green");
  5.         return this; // 支持链式调用
  6.     };
  7. }(jQuery));
  8. // 使用插件
  9. $("a").greenify().addClass("greenified");
复制代码
  1. (function($) {
  2.     $.fn.greenify = function(options) {
  3.         // 设置默认值
  4.         var settings = $.extend({
  5.             color: "#556b2f",
  6.             backgroundColor: "white"
  7.         }, options);
  8.         
  9.         // 应用设置
  10.         return this.css({
  11.             color: settings.color,
  12.             backgroundColor: settings.backgroundColor
  13.         });
  14.     };
  15. }(jQuery));
  16. // 使用带选项的插件
  17. $("div").greenify({
  18.     color: "orange"
  19. });
复制代码
  1. (function($) {
  2.     var methods = {
  3.         init: function(options) {
  4.             // 初始化代码
  5.         },
  6.         show: function() {
  7.             // 显示代码
  8.         },
  9.         hide: function() {
  10.             // 隐藏代码
  11.         },
  12.         update: function(content) {
  13.             // 更新代码
  14.         }
  15.     };
  16.    
  17.     $.fn.tooltip = function(method) {
  18.         // 方法调用
  19.         if (methods[method]) {
  20.             return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  21.         } else if (typeof method === 'object' || !method) {
  22.             return methods.init.apply(this, arguments);
  23.         } else {
  24.             $.error('Method ' + method + ' does not exist on jQuery.tooltip');
  25.         }
  26.     };
  27. }(jQuery));
  28. // 使用带方法的插件
  29. $('div').tooltip(); // 初始化
  30. $('div').tooltip('show'); // 调用show方法
  31. $('div').tooltip('hide'); // 调用hide方法
  32. $('div').tooltip('update', '新内容'); // 调用update方法
复制代码

4. 实例教程

4.1 表单验证实例
  1. $(document).ready(function() {
  2.     // 表单验证
  3.     $("#myForm").submit(function(event) {
  4.         var isValid = true;
  5.         
  6.         // 验证用户名
  7.         var username = $("#username").val();
  8.         if (username.length < 3) {
  9.             $("#usernameError").text("用户名必须至少3个字符");
  10.             isValid = false;
  11.         } else {
  12.             $("#usernameError").text("");
  13.         }
  14.         
  15.         // 验证邮箱
  16.         var email = $("#email").val();
  17.         var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
  18.         if (!emailRegex.test(email)) {
  19.             $("#emailError").text("请输入有效的邮箱地址");
  20.             isValid = false;
  21.         } else {
  22.             $("#emailError").text("");
  23.         }
  24.         
  25.         // 验证密码
  26.         var password = $("#password").val();
  27.         if (password.length < 6) {
  28.             $("#passwordError").text("密码必须至少6个字符");
  29.             isValid = false;
  30.         } else {
  31.             $("#passwordError").text("");
  32.         }
  33.         
  34.         // 验证确认密码
  35.         var confirmPassword = $("#confirmPassword").val();
  36.         if (password !== confirmPassword) {
  37.             $("#confirmPasswordError").text("两次输入的密码不匹配");
  38.             isValid = false;
  39.         } else {
  40.             $("#confirmPasswordError").text("");
  41.         }
  42.         
  43.         // 如果表单无效,阻止提交
  44.         if (!isValid) {
  45.             event.preventDefault();
  46.         }
  47.     });
  48.    
  49.     // 实时验证
  50.     $("#username").on("input", function() {
  51.         var username = $(this).val();
  52.         if (username.length < 3) {
  53.             $("#usernameError").text("用户名必须至少3个字符");
  54.         } else {
  55.             $("#usernameError").text("");
  56.         }
  57.     });
  58.    
  59.     $("#email").on("input", function() {
  60.         var email = $(this).val();
  61.         var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
  62.         if (!emailRegex.test(email)) {
  63.             $("#emailError").text("请输入有效的邮箱地址");
  64.         } else {
  65.             $("#emailError").text("");
  66.         }
  67.     });
  68.    
  69.     $("#password").on("input", function() {
  70.         var password = $(this).val();
  71.         if (password.length < 6) {
  72.             $("#passwordError").text("密码必须至少6个字符");
  73.         } else {
  74.             $("#passwordError").text("");
  75.         }
  76.         
  77.         // 检查确认密码
  78.         var confirmPassword = $("#confirmPassword").val();
  79.         if (confirmPassword && password !== confirmPassword) {
  80.             $("#confirmPasswordError").text("两次输入的密码不匹配");
  81.         } else {
  82.             $("#confirmPasswordError").text("");
  83.         }
  84.     });
  85.    
  86.     $("#confirmPassword").on("input", function() {
  87.         var confirmPassword = $(this).val();
  88.         var password = $("#password").val();
  89.         if (password !== confirmPassword) {
  90.             $("#confirmPasswordError").text("两次输入的密码不匹配");
  91.         } else {
  92.             $("#confirmPasswordError").text("");
  93.         }
  94.     });
  95. });
复制代码

4.2 图片轮播实例
  1. $(document).ready(function() {
  2.     // 设置轮播间隔时间(毫秒)
  3.     var intervalTime = 3000;
  4.    
  5.     // 获取轮播图片数量
  6.     var slideCount = $('#slider ul li').length;
  7.    
  8.     // 计算轮播宽度
  9.     var slideWidth = $('#slider').width();
  10.    
  11.     // 计算总宽度
  12.     var totalWidth = slideCount * slideWidth;
  13.    
  14.     // 设置轮播列表宽度
  15.     $('#slider ul').css('width', totalWidth);
  16.    
  17.     // 添加导航点
  18.     for (var i = 0; i < slideCount; i++) {
  19.         $('#slider-nav').append('<a href="#" class="slide-nav" data-index="' + i + '"></a>');
  20.     }
  21.    
  22.     // 激活第一个导航点
  23.     $('#slider-nav a:first-child').addClass('active');
  24.    
  25.     // 自动轮播函数
  26.     function autoSlide() {
  27.         var currentSlide = parseInt($('#slider ul').css('margin-left')) / slideWidth;
  28.         var nextSlide = currentSlide - 1;
  29.         
  30.         if (nextSlide < -(slideCount - 1)) {
  31.             nextSlide = 0;
  32.         }
  33.         
  34.         moveSlider(nextSlide);
  35.     }
  36.    
  37.     // 移动轮播函数
  38.     function moveSlider(slideIndex) {
  39.         var slidePosition = slideIndex * slideWidth;
  40.         $('#slider ul').animate({
  41.             'margin-left': -slidePosition
  42.         }, 500);
  43.         
  44.         // 更新导航点状态
  45.         $('#slider-nav a').removeClass('active');
  46.         $('#slider-nav a[data-index="' + (-slideIndex) + '"]').addClass('active');
  47.     }
  48.    
  49.     // 设置自动轮播定时器
  50.     var timer = setInterval(autoSlide, intervalTime);
  51.    
  52.     // 鼠标悬停时停止轮播
  53.     $('#slider').hover(
  54.         function() {
  55.             clearInterval(timer);
  56.         },
  57.         function() {
  58.             timer = setInterval(autoSlide, intervalTime);
  59.         }
  60.     );
  61.    
  62.     // 点击导航点切换轮播
  63.     $('#slider-nav a').click(function(e) {
  64.         e.preventDefault();
  65.         var slideIndex = $(this).data('index');
  66.         moveSlider(-slideIndex);
  67.     });
  68.    
  69.     // 点击上一张按钮
  70.     $('#prev').click(function(e) {
  71.         e.preventDefault();
  72.         var currentSlide = parseInt($('#slider ul').css('margin-left')) / slideWidth;
  73.         var prevSlide = currentSlide + 1;
  74.         
  75.         if (prevSlide > 0) {
  76.             prevSlide = -(slideCount - 1);
  77.         }
  78.         
  79.         moveSlider(prevSlide);
  80.     });
  81.    
  82.     // 点击下一张按钮
  83.     $('#next').click(function(e) {
  84.         e.preventDefault();
  85.         var currentSlide = parseInt($('#slider ul').css('margin-left')) / slideWidth;
  86.         var nextSlide = currentSlide - 1;
  87.         
  88.         if (nextSlide < -(slideCount - 1)) {
  89.             nextSlide = 0;
  90.         }
  91.         
  92.         moveSlider(nextSlide);
  93.     });
  94.    
  95.     // 响应式调整
  96.     $(window).resize(function() {
  97.         slideWidth = $('#slider').width();
  98.         totalWidth = slideCount * slideWidth;
  99.         $('#slider ul').css('width', totalWidth);
  100.         
  101.         // 调整当前位置
  102.         var currentSlide = parseInt($('#slider ul').css('margin-left')) / slideWidth;
  103.         var newSlidePosition = currentSlide * slideWidth;
  104.         $('#slider ul').css('margin-left', newSlidePosition);
  105.     });
  106. });
复制代码

4.3 AJAX加载内容实例
  1. $(document).ready(function() {
  2.     // 加载文章列表
  3.     function loadArticles(page) {
  4.         // 显示加载指示器
  5.         $("#loading").show();
  6.         
  7.         // 发送AJAX请求
  8.         $.ajax({
  9.             url: "get_articles.php",
  10.             type: "GET",
  11.             data: { page: page },
  12.             dataType: "json",
  13.             success: function(response) {
  14.                 // 隐藏加载指示器
  15.                 $("#loading").hide();
  16.                
  17.                 // 清空当前文章列表
  18.                 $("#articles").empty();
  19.                
  20.                 // 添加新文章
  21.                 if (response.articles.length > 0) {
  22.                     $.each(response.articles, function(index, article) {
  23.                         var articleHtml = '<div class="article">';
  24.                         articleHtml += '<h2>' + article.title + '</h2>';
  25.                         articleHtml += '<div class="meta">发布于 ' + article.date + ' 作者:' + article.author + '</div>';
  26.                         articleHtml += '<div class="content">' + article.content + '</div>';
  27.                         articleHtml += '<div class="actions">';
  28.                         articleHtml += '<button class="read-more" data-id="' + article.id + '">阅读更多</button>';
  29.                         articleHtml += '<button class="like" data-id="' + article.id + '">点赞 (' + article.likes + ')</button>';
  30.                         articleHtml += '</div>';
  31.                         articleHtml += '</div>';
  32.                         
  33.                         $("#articles").append(articleHtml);
  34.                     });
  35.                     
  36.                     // 更新分页
  37.                     updatePagination(response.currentPage, response.totalPages);
  38.                 } else {
  39.                     $("#articles").html("<p>没有找到文章。</p>");
  40.                 }
  41.             },
  42.             error: function(xhr, status, error) {
  43.                 // 隐藏加载指示器
  44.                 $("#loading").hide();
  45.                
  46.                 // 显示错误信息
  47.                 $("#articles").html("<p>加载文章时出错: " + error + "</p>");
  48.             }
  49.         });
  50.     }
  51.    
  52.     // 更新分页
  53.     function updatePagination(currentPage, totalPages) {
  54.         $("#pagination").empty();
  55.         
  56.         // 上一页按钮
  57.         if (currentPage > 1) {
  58.             $("#pagination").append('<button class="page-btn" data-page="' + (currentPage - 1) + '">上一页</button>');
  59.         }
  60.         
  61.         // 页码按钮
  62.         for (var i = 1; i <= totalPages; i++) {
  63.             if (i === currentPage) {
  64.                 $("#pagination").append('<button class="page-btn active" data-page="' + i + '">' + i + '</button>');
  65.             } else {
  66.                 $("#pagination").append('<button class="page-btn" data-page="' + i + '">' + i + '</button>');
  67.             }
  68.         }
  69.         
  70.         // 下一页按钮
  71.         if (currentPage < totalPages) {
  72.             $("#pagination").append('<button class="page-btn" data-page="' + (currentPage + 1) + '">下一页</button>');
  73.         }
  74.     }
  75.    
  76.     // 加载第一页
  77.     loadArticles(1);
  78.    
  79.     // 分页按钮点击事件
  80.     $(document).on("click", ".page-btn", function() {
  81.         var page = $(this).data("page");
  82.         loadArticles(page);
  83.         
  84.         // 滚动到顶部
  85.         $("html, body").animate({ scrollTop: 0 }, "slow");
  86.     });
  87.    
  88.     // 阅读更多按钮点击事件
  89.     $(document).on("click", ".read-more", function() {
  90.         var articleId = $(this).data("id");
  91.         
  92.         // 显示加载指示器
  93.         $("#loading").show();
  94.         
  95.         // 发送AJAX请求获取完整文章
  96.         $.ajax({
  97.             url: "get_article.php",
  98.             type: "GET",
  99.             data: { id: articleId },
  100.             dataType: "json",
  101.             success: function(response) {
  102.                 // 隐藏加载指示器
  103.                 $("#loading").hide();
  104.                
  105.                 // 显示文章详情模态框
  106.                 $("#modal-title").text(response.title);
  107.                 $("#modal-content").html(response.fullContent);
  108.                 $("#modal-meta").text("发布于 " + response.date + " 作者:" + response.author);
  109.                 $("#article-modal").show();
  110.             },
  111.             error: function(xhr, status, error) {
  112.                 // 隐藏加载指示器
  113.                 $("#loading").hide();
  114.                
  115.                 // 显示错误信息
  116.                 alert("加载文章详情时出错: " + error);
  117.             }
  118.         });
  119.     });
  120.    
  121.     // 点赞按钮点击事件
  122.     $(document).on("click", ".like", function() {
  123.         var button = $(this);
  124.         var articleId = button.data("id");
  125.         
  126.         // 发送AJAX请求点赞
  127.         $.ajax({
  128.             url: "like_article.php",
  129.             type: "POST",
  130.             data: { id: articleId },
  131.             dataType: "json",
  132.             success: function(response) {
  133.                 if (response.success) {
  134.                     // 更新点赞数
  135.                     button.text("点赞 (" + response.likes + ")");
  136.                     
  137.                     // 添加点赞动画效果
  138.                     button.addClass("liked");
  139.                     setTimeout(function() {
  140.                         button.removeClass("liked");
  141.                     }, 1000);
  142.                 } else {
  143.                     alert(response.message);
  144.                 }
  145.             },
  146.             error: function(xhr, status, error) {
  147.                 alert("点赞时出错: " + error);
  148.             }
  149.         });
  150.     });
  151.    
  152.     // 关闭模态框
  153.     $(".close-modal").click(function() {
  154.         $("#article-modal").hide();
  155.     });
  156.    
  157.     // 点击模态框外部关闭模态框
  158.     $(window).click(function(event) {
  159.         if ($(event.target).is("#article-modal")) {
  160.             $("#article-modal").hide();
  161.         }
  162.     });
  163. });
复制代码

4.4 拖放功能实例
  1. $(document).ready(function() {
  2.     // 使元素可拖动
  3.     $(".draggable").draggable({
  4.         revert: "invalid", // 如果不被接受,则返回原位置
  5.         cursor: "move",
  6.         start: function(event, ui) {
  7.             // 拖动开始时的操作
  8.             $(this).css("opacity", "0.7");
  9.         },
  10.         stop: function(event, ui) {
  11.             // 拖动结束时的操作
  12.             $(this).css("opacity", "1");
  13.         }
  14.     });
  15.    
  16.     // 设置放置区域
  17.     $(".droppable").droppable({
  18.         accept: ".draggable", // 接受的元素
  19.         hoverClass: "droppable-hover", // 悬停时的样式
  20.         drop: function(event, ui) {
  21.             // 放置时的操作
  22.             var draggedItem = ui.draggable;
  23.             var droppedIn = $(this);
  24.             
  25.             // 复制拖动的元素到放置区域
  26.             var clone = draggedItem.clone();
  27.             clone.draggable({
  28.                 revert: "invalid",
  29.                 cursor: "move"
  30.             });
  31.             
  32.             droppedIn.append(clone);
  33.             
  34.             // 添加放置效果
  35.             droppedIn.addClass("dropped");
  36.             setTimeout(function() {
  37.                 droppedIn.removeClass("dropped");
  38.             }, 500);
  39.             
  40.             // 更新计数
  41.             updateCounts();
  42.         },
  43.         out: function(event, ui) {
  44.             // 离开放置区域时的操作
  45.             $(this).removeClass("droppable-hover");
  46.         }
  47.     });
  48.    
  49.     // 更新计数函数
  50.     function updateCounts() {
  51.         // 更新源区域的计数
  52.         $("#source-count").text($("#source .draggable").length);
  53.         
  54.         // 更新目标区域的计数
  55.         $("#target-count").text($("#target .draggable").length);
  56.     }
  57.    
  58.     // 初始化计数
  59.     updateCounts();
  60.    
  61.     // 添加重置按钮功能
  62.     $("#reset").click(function() {
  63.         // 清空目标区域
  64.         $("#target").empty();
  65.         
  66.         // 重置源区域
  67.         $("#source").html(
  68.             '<div class="draggable" id="item1">项目 1</div>' +
  69.             '<div class="draggable" id="item2">项目 2</div>' +
  70.             '<div class="draggable" id="item3">项目 3</div>' +
  71.             '<div class="draggable" id="item4">项目 4</div>' +
  72.             '<div class="draggable" id="item5">项目 5</div>'
  73.         );
  74.         
  75.         // 重新使元素可拖动
  76.         $(".draggable").draggable({
  77.             revert: "invalid",
  78.             cursor: "move",
  79.             start: function(event, ui) {
  80.                 $(this).css("opacity", "0.7");
  81.             },
  82.             stop: function(event, ui) {
  83.                 $(this).css("opacity", "1");
  84.             }
  85.         });
  86.         
  87.         // 更新计数
  88.         updateCounts();
  89.     });
  90.    
  91.     // 添加排序功能
  92.     $("#source, #target").sortable({
  93.         connectWith: ".connected-sortable", // 连接可排序区域
  94.         placeholder: "sortable-placeholder", // 占位符样式
  95.         tolerance: "pointer", // 指定用于测试项目是否在另一项目上的模式
  96.         cursor: "move",
  97.         opacity: 0.7,
  98.         update: function(event, ui) {
  99.             // 排序更新时的操作
  100.             updateCounts();
  101.         }
  102.     }).disableSelection(); // 防止文本选择
  103. });
复制代码

5. 常见问题解答

5.1 jQuery与其他库冲突问题

问题:当我在同一页面使用jQuery和其他JavaScript库(如Prototype、MooTools等)时,出现冲突,导致代码无法正常工作。

解决方案:

jQuery使用$作为其别名,但其他库也可能使用$符号。为了解决冲突,jQuery提供了noConflict()方法:
  1. // 方法1:完全放弃$控制权
  2. jQuery.noConflict();
  3. // 现在可以使用jQuery代替$
  4. jQuery(document).ready(function(){
  5.     jQuery("p").text("Hello, world!");
  6. });
  7. // 方法2:自定义别名
  8. var jq = jQuery.noConflict();
  9. // 使用jq作为jQuery的别名
  10. jq(document).ready(function(){
  11.     jq("p").text("Hello, world!");
  12. });
  13. // 方法3:在内部使用$
  14. jQuery.noConflict();
  15. jQuery(document).ready(function($) {
  16.     // 在这个函数内部,$仍然指向jQuery
  17.     $("p").text("Hello, world!");
  18. });
  19. // 方法4:使用立即执行函数表达式(IIFE)
  20. jQuery.noConflict();
  21. (function($) {
  22.     $(function() {
  23.         // $在这里指向jQuery
  24.         $("p").text("Hello, world!");
  25.     });
  26. })(jQuery);
复制代码

5.2 jQuery选择器性能问题

问题:我的页面中有大量元素,使用jQuery选择器时性能很差,页面响应缓慢。

解决方案:

优化jQuery选择器性能的几种方法:
  1. // 1. 使用ID选择器
  2. // 快速
  3. $("#myId");
  4. // 慢速
  5. $("div#myId");
  6. // 2. 缓存选择器结果
  7. // 不好的做法
  8. for (var i = 0; i < 100; i++) {
  9.     $("#myElement").append(i);
  10. }
  11. // 好的做法
  12. var myElement = $("#myElement");
  13. for (var i = 0; i < 100; i++) {
  14.     myElement.append(i);
  15. }
  16. // 3. 使用find()代替上下文选择器
  17. // 不好的做法
  18. $("div", "#myContainer");
  19. // 好的做法
  20. $("#myContainer").find("div");
  21. // 4. 避免通用选择器
  22. // 不好的做法
  23. $(".container > *");
  24. // 好的做法
  25. $(".container").children();
  26. // 5. 使用更具体的选择器
  27. // 不好的做法
  28. $("div.data");
  29. // 好的做法
  30. $("div.data-table");
  31. // 6. 使用原生DOM方法获取元素,然后传递给jQuery
  32. // 不好的做法
  33. $("#myId .myClass");
  34. // 好的做法
  35. var element = document.getElementById("myId");
  36. var myElements = $(element).find(".myClass");
复制代码

5.3 AJAX请求缓存问题

问题:在IE浏览器中,我的AJAX请求被缓存,导致我获取不到最新的数据。

解决方案:
  1. // 方法1:禁用AJAX缓存(全局设置)
  2. $.ajaxSetup({
  3.     cache: false
  4. });
  5. // 方法2:在单个AJAX请求中禁用缓存
  6. $.ajax({
  7.     url: "myurl.php",
  8.     cache: false,
  9.     success: function(data) {
  10.         // 处理数据
  11.     }
  12. });
  13. // 方法3:在URL中添加时间戳或随机数
  14. $.ajax({
  15.     url: "myurl.php?t=" + new Date().getTime(),
  16.     success: function(data) {
  17.         // 处理数据
  18.     }
  19. });
  20. // 方法4:使用POST方法代替GET方法
  21. $.ajax({
  22.     type: "POST",
  23.     url: "myurl.php",
  24.     success: function(data) {
  25.         // 处理数据
  26.     }
  27. });
复制代码

5.4 事件委托问题

问题:我动态添加了元素到页面中,但是这些元素上的事件处理程序不起作用。

解决方案:

使用事件委托(Event Delegation)来处理动态添加的元素:
  1. // 不好的做法 - 直接绑定事件
  2. $(".myButton").click(function() {
  3.     alert("按钮被点击");
  4. });
  5. // 动态添加按钮
  6. $("#container").append("<button class='myButton'>新按钮</button>");
  7. // 这个新按钮不会响应点击事件
  8. // 好的做法 - 使用事件委托
  9. $("#container").on("click", ".myButton", function() {
  10.     alert("按钮被点击");
  11. });
  12. // 动态添加按钮
  13. $("#container").append("<button class='myButton'>新按钮</button>");
  14. // 这个新按钮会响应点击事件
  15. // 对于jQuery 1.11,也可以使用delegate()方法
  16. $("#container").delegate(".myButton", "click", function() {
  17.     alert("按钮被点击");
  18. });
复制代码

5.5 动画队列问题

问题:当用户快速多次触发动画时,动画效果会排队执行,导致动画效果与用户操作不同步。

解决方案:
  1. // 不好的做法
  2. $("#myElement").hover(
  3.     function() {
  4.         $(this).animate({height: "200px"}, 500);
  5.     },
  6.     function() {
  7.         $(this).animate({height: "100px"}, 500);
  8.     }
  9. );
  10. // 好的做法 - 使用stop()方法
  11. $("#myElement").hover(
  12.     function() {
  13.         $(this).stop().animate({height: "200px"}, 500);
  14.     },
  15.     function() {
  16.         $(this).stop().animate({height: "100px"}, 500);
  17.     }
  18. );
  19. // 更好的做法 - 使用stop(true, true)
  20. $("#myElement").hover(
  21.     function() {
  22.         $(this).stop(true, true).animate({height: "200px"}, 500);
  23.     },
  24.     function() {
  25.         $(this).stop(true, true).animate({height: "100px"}, 500);
  26.     }
  27. );
  28. // 或者使用finish()方法(jQuery 1.9+)
  29. $("#myElement").hover(
  30.     function() {
  31.         $(this).finish().animate({height: "200px"}, 500);
  32.     },
  33.     function() {
  34.         $(this).finish().animate({height: "100px"}, 500);
  35.     }
  36. );
复制代码

5.6 内存泄漏问题

问题:我的单页应用在使用一段时间后变得越来越慢,内存使用量不断增加。

解决方案:
  1. // 1. 解除不再需要的事件绑定
  2. function setupEvents() {
  3.     $("#myButton").on("click", handleClick);
  4. }
  5. function cleanupEvents() {
  6.     $("#myButton").off("click", handleClick);
  7. }
  8. // 2. 在移除元素前解除事件绑定
  9. $("#myElement").remove(); // 这会自动解除事件绑定
  10. // 或者
  11. $("#myElement").empty(); // 这会解除所有子元素的事件绑定
  12. // 3. 使用命名空间事件,便于批量解除
  13. $("#myElement").on("click.myNamespace", function() {
  14.     // 处理点击事件
  15. });
  16. // 解除特定命名空间的所有事件
  17. $("#myElement").off(".myNamespace");
  18. // 4. 避免在循环中创建闭包
  19. // 不好的做法
  20. for (var i = 0; i < 10; i++) {
  21.     $("#myElement" + i).click(function() {
  22.         alert("元素 " + i + " 被点击"); // 这总是显示10
  23.     });
  24. }
  25. // 好的做法
  26. for (var i = 0; i < 10; i++) {
  27.     (function(index) {
  28.         $("#myElement" + index).click(function() {
  29.             alert("元素 " + index + " 被点击");
  30.         });
  31.     })(i);
  32. }
  33. // 5. 使用data()方法存储数据而不是DOM属性
  34. // 不好的做法
  35. $("#myElement").attr("data-mydata", JSON.stringify(largeObject));
  36. // 好的做法
  37. $("#myElement").data("mydata", largeObject);
  38. // 6. 在不再需要时清除数据
  39. $("#myElement").removeData("mydata");
复制代码

5.7 跨域请求问题

问题:当我尝试从不同的域获取数据时,浏览器阻止了我的AJAX请求。

解决方案:
  1. // 方法1:使用JSONP
  2. $.ajax({
  3.     url: "https://example.com/data",
  4.     dataType: "jsonp",
  5.     success: function(data) {
  6.         // 处理数据
  7.     }
  8. });
  9. // 方法2:使用CORS(需要服务器支持)
  10. $.ajax({
  11.     url: "https://example.com/data",
  12.     xhrFields: {
  13.         withCredentials: true
  14.     },
  15.     crossDomain: true,
  16.     success: function(data) {
  17.         // 处理数据
  18.     }
  19. });
  20. // 方法3:使用服务器代理
  21. // 在同域的服务器上创建一个代理脚本,然后通过该脚本请求跨域数据
  22. $.ajax({
  23.     url: "/proxy.php?url=" + encodeURIComponent("https://example.com/data"),
  24.     success: function(data) {
  25.         // 处理数据
  26.     }
  27. });
  28. // proxy.php示例代码
  29. /*
  30. <?php
  31. $url = $_GET['url'];
  32. echo file_get_contents($url);
  33. ?>
  34. */
复制代码

6. 最佳实践和性能优化

6.1 代码组织最佳实践
  1. // 1. 使用立即执行函数表达式(IIFE)避免全局变量污染
  2. (function($) {
  3.     // 你的jQuery代码在这里
  4.    
  5.     // 定义私有变量和函数
  6.     var privateVar = "I'm private";
  7.    
  8.     function privateFunction() {
  9.         // 私有函数实现
  10.     }
  11.    
  12.     // 定义公共API
  13.     $.fn.myPlugin = function(options) {
  14.         // 插件实现
  15.     };
  16.    
  17. })(jQuery);
  18. // 2. 使用对象字面量组织代码
  19. var myApp = {
  20.     settings: {
  21.         apiUrl: "https://api.example.com",
  22.         timeout: 5000
  23.     },
  24.    
  25.     init: function() {
  26.         this.cacheDom();
  27.         this.bindEvents();
  28.         this.loadData();
  29.     },
  30.    
  31.     cacheDom: function() {
  32.         this.$container = $("#container");
  33.         this.$button = $("#button");
  34.     },
  35.    
  36.     bindEvents: function() {
  37.         var self = this;
  38.         this.$button.on("click", function() {
  39.             self.handleButtonClick();
  40.         });
  41.     },
  42.    
  43.     handleButtonClick: function() {
  44.         // 处理按钮点击
  45.     },
  46.    
  47.     loadData: function() {
  48.         var self = this;
  49.         $.ajax({
  50.             url: this.settings.apiUrl,
  51.             timeout: this.settings.timeout,
  52.             success: function(data) {
  53.                 self.processData(data);
  54.             },
  55.             error: function() {
  56.                 self.handleError();
  57.             }
  58.         });
  59.     },
  60.    
  61.     processData: function(data) {
  62.         // 处理数据
  63.     },
  64.    
  65.     handleError: function() {
  66.         // 处理错误
  67.     }
  68. };
  69. // 初始化应用
  70. $(document).ready(function() {
  71.     myApp.init();
  72. });
  73. // 3. 使用模块模式
  74. var Module = (function($) {
  75.     // 私有变量
  76.     var privateVar = "I'm private";
  77.    
  78.     // 私有函数
  79.     function privateFunction() {
  80.         return privateVar;
  81.     }
  82.    
  83.     // 返回公共API
  84.     return {
  85.         publicVar: "I'm public",
  86.         publicFunction: function() {
  87.             return privateFunction();
  88.         }
  89.     };
  90. })(jQuery);
  91. // 使用模块
  92. console.log(Module.publicVar); // "I'm public"
  93. console.log(Module.publicFunction()); // "I'm private"
  94. console.log(Module.privateVar); // undefined
  95. console.log(Module.privateFunction()); // TypeError
复制代码

6.2 性能优化技巧
  1. // 1. 缓存jQuery对象
  2. // 不好的做法
  3. function updateElements() {
  4.     $("#element1").addClass("active");
  5.     $("#element2").addClass("active");
  6.     $("#element3").addClass("active");
  7. }
  8. // 好的做法
  9. function updateElements() {
  10.     var $element1 = $("#element1");
  11.     var $element2 = $("#element2");
  12.     var $element3 = $("#element3");
  13.    
  14.     $element1.addClass("active");
  15.     $element2.addClass("active");
  16.     $element3.addClass("active");
  17. }
  18. // 2. 使用链式调用减少DOM查询
  19. // 不好的做法
  20. $("#myElement").addClass("active");
  21. $("#myElement").css("color", "red");
  22. $("#myElement").show();
  23. // 好的做法
  24. $("#myElement").addClass("active").css("color", "red").show();
  25. // 3. 批量DOM操作
  26. // 不好的做法
  27. for (var i = 0; i < 100; i++) {
  28.     $("#container").append("<div>Item " + i + "</div>");
  29. }
  30. // 好的做法
  31. var items = [];
  32. for (var i = 0; i < 100; i++) {
  33.     items.push("<div>Item " + i + "</div>");
  34. }
  35. $("#container").append(items.join(""));
  36. // 4. 使用文档片段
  37. var fragment = document.createDocumentFragment();
  38. for (var i = 0; i < 100; i++) {
  39.     var div = document.createElement("div");
  40.     div.textContent = "Item " + i;
  41.     fragment.appendChild(div);
  42. }
  43. $("#container").append(fragment);
  44. // 5. 事件委托
  45. // 不好的做法
  46. $(".item").click(function() {
  47.     // 处理点击
  48. });
  49. // 好的做法
  50. $("#container").on("click", ".item", function() {
  51.     // 处理点击
  52. });
  53. // 6. 减少重绘和回流
  54. // 不好的做法
  55. var element = document.getElementById("myElement");
  56. element.style.width = "100px";
  57. element.style.height = "100px";
  58. element.style.backgroundColor = "red";
  59. // 好的做法
  60. var element = document.getElementById("myElement");
  61. element.style.cssText = "width: 100px; height: 100px; background-color: red;";
  62. // 7. 使用原生方法代替jQuery方法
  63. // 不好的做法
  64. var id = $("#myElement").attr("id");
  65. // 好的做法
  66. var id = document.getElementById("myElement").id;
  67. // 8. 延迟加载
  68. // 不好的做法
  69. $(document).ready(function() {
  70.     // 加载所有资源
  71.     loadAllResources();
  72. });
  73. // 好的做法
  74. $(document).ready(function() {
  75.     // 只加载必要的资源
  76.     loadEssentialResources();
  77.    
  78.     // 延迟加载其他资源
  79.     setTimeout(loadNonEssentialResources, 2000);
  80. });
  81. // 9. 使用requestAnimationFrame进行动画
  82. // 不好的做法
  83. function animate() {
  84.     $("#myElement").css("left", "+=1px");
  85.     setTimeout(animate, 16);
  86. }
  87. // 好的做法
  88. function animate() {
  89.     $("#myElement").css("left", "+=1px");
  90.     requestAnimationFrame(animate);
  91. }
复制代码

6.3 错误处理和调试
  1. // 1. 全局AJAX错误处理
  2. $(document).ajaxError(function(event, jqXHR, settings, thrownError) {
  3.     console.error("AJAX错误:", thrownError);
  4.     console.error("URL:", settings.url);
  5.     console.error("状态:", jqXHR.status);
  6.     console.error("响应文本:", jqXHR.responseText);
  7.    
  8.     // 显示用户友好的错误消息
  9.     showError("发生了一个错误,请稍后再试。");
  10. });
  11. // 2. 封装AJAX调用以便统一处理错误
  12. function safeAjax(options) {
  13.     var defaultOptions = {
  14.         error: function(jqXHR, textStatus, errorThrown) {
  15.             console.error("AJAX错误:", textStatus, errorThrown);
  16.             showError("请求失败,请稍后再试。");
  17.         },
  18.         timeout: 10000 // 10秒超时
  19.     };
  20.    
  21.     return $.ajax($.extend({}, defaultOptions, options));
  22. }
  23. // 使用封装的AJAX函数
  24. safeAjax({
  25.     url: "/api/data",
  26.     success: function(data) {
  27.         processData(data);
  28.     }
  29. });
  30. // 3. 使用try-catch处理可能的错误
  31. function riskyOperation() {
  32.     try {
  33.         // 可能出错的代码
  34.         var result = potentiallyRiskyFunction();
  35.         return result;
  36.     } catch (error) {
  37.         console.error("操作失败:", error);
  38.         showError("操作失败,请稍后再试。");
  39.         return null;
  40.     }
  41. }
  42. // 4. 使用jQuery的deferred对象处理异步操作
  43. function fetchData() {
  44.     var deferred = $.Deferred();
  45.    
  46.     $.ajax({
  47.         url: "/api/data",
  48.         success: function(data) {
  49.             deferred.resolve(data);
  50.         },
  51.         error: function() {
  52.             deferred.reject("获取数据失败");
  53.         }
  54.     });
  55.    
  56.     return deferred.promise();
  57. }
  58. // 使用deferred对象
  59. fetchData().done(function(data) {
  60.     processData(data);
  61. }).fail(function(error) {
  62.     showError(error);
  63. });
  64. // 5. 使用console.log进行调试
  65. function debugLog(message) {
  66.     if (window.console && window.console.log) {
  67.         console.log(message);
  68.     }
  69. }
  70. // 6. 使用jQuery的data方法存储调试信息
  71. $("#myElement").data("debug", {
  72.     created: new Date(),
  73.     createdBy: "John Doe",
  74.     purpose: "Example element"
  75. });
  76. // 检索调试信息
  77. var debugInfo = $("#myElement").data("debug");
  78. console.log(debugInfo);
复制代码

7. jQuery与其他库的集成

7.1 jQuery与Bootstrap集成
  1. // 1. 使用Bootstrap的模态框
  2. $(document).ready(function() {
  3.     // 显示模态框
  4.     $("#showModalBtn").click(function() {
  5.         $("#myModal").modal("show");
  6.     });
  7.    
  8.     // 隐藏模态框
  9.     $("#hideModalBtn").click(function() {
  10.         $("#myModal").modal("hide");
  11.     });
  12.    
  13.     // 监听模态框事件
  14.     $("#myModal").on("show.bs.modal", function(e) {
  15.         console.log("模态框即将显示");
  16.     });
  17.    
  18.     $("#myModal").on("shown.bs.modal", function(e) {
  19.         console.log("模态框已显示");
  20.     });
  21.    
  22.     $("#myModal").on("hide.bs.modal", function(e) {
  23.         console.log("模态框即将隐藏");
  24.     });
  25.    
  26.     $("#myModal").on("hidden.bs.modal", function(e) {
  27.         console.log("模态框已隐藏");
  28.     });
  29. });
  30. // 2. 使用Bootstrap的标签页
  31. $(document).ready(function() {
  32.     // 监听标签页切换事件
  33.     $('a[data-toggle="tab"]').on("shown.bs.tab", function(e) {
  34.         var target = $(e.target).attr("href"); // 激活的标签页
  35.         var previous = $(e.relatedTarget).attr("href"); // 上一个标签页
  36.         
  37.         console.log("切换到: " + target);
  38.         console.log("上一个: " + previous);
  39.     });
  40.    
  41.     // 通过JavaScript激活标签页
  42.     $("#activateTabBtn").click(function() {
  43.         $('#myTabs a[href="#profile"]').tab("show");
  44.     });
  45. });
  46. // 3. 使用Bootstrap的警告框
  47. $(document).ready(function() {
  48.     // 关闭警告框
  49.     $(".alert").alert();
  50.    
  51.     // 监听关闭事件
  52.     $("#myAlert").on("close.bs.alert", function() {
  53.         console.log("警告框即将关闭");
  54.     });
  55.    
  56.     $("#myAlert").on("closed.bs.alert", function() {
  57.         console.log("警告框已关闭");
  58.     });
  59.    
  60.     // 通过JavaScript关闭警告框
  61.     $("#closeAlertBtn").click(function() {
  62.         $("#myAlert").alert("close");
  63.     });
  64. });
  65. // 4. 使用Bootstrap的下拉菜单
  66. $(document).ready(function() {
  67.     // 监听下拉菜单事件
  68.     $(".dropdown").on("show.bs.dropdown", function() {
  69.         console.log("下拉菜单即将显示");
  70.     });
  71.    
  72.     $(".dropdown").on("shown.bs.dropdown", function() {
  73.         console.log("下拉菜单已显示");
  74.     });
  75.    
  76.     $(".dropdown").on("hide.bs.dropdown", function() {
  77.         console.log("下拉菜单即将隐藏");
  78.     });
  79.    
  80.     $(".dropdown").on("hidden.bs.dropdown", function() {
  81.         console.log("下拉菜单已隐藏");
  82.     });
  83.    
  84.     // 通过JavaScript切换下拉菜单
  85.     $("#toggleDropdownBtn").click(function() {
  86.         $("#myDropdown").dropdown("toggle");
  87.     });
  88. });
复制代码

7.2 jQuery与AngularJS集成
  1. // 1. 在AngularJS控制器中使用jQuery
  2. angular.module("myApp", []).controller("myController", function($scope) {
  3.     // 使用jQuery选择元素
  4.     $scope.init = function() {
  5.         // 等待DOM渲染完成
  6.         setTimeout(function() {
  7.             // 使用jQuery操作DOM
  8.             $("#myElement").addClass("highlight");
  9.             
  10.             // 使用jQuery绑定事件
  11.             $("#myButton").click(function() {
  12.                 $scope.$apply(function() {
  13.                     $scope.message = "按钮被点击";
  14.                 });
  15.             });
  16.         }, 0);
  17.     };
  18.    
  19.     $scope.init();
  20. });
  21. // 2. 在AngularJS指令中使用jQuery
  22. angular.module("myApp").directive("myDirective", function() {
  23.     return {
  24.         restrict: "A",
  25.         link: function(scope, element, attrs) {
  26.             // element是一个jQuery对象(如果jQuery在Angular之前加载)
  27.             element.css("color", "red");
  28.             
  29.             // 使用jQuery事件
  30.             element.on("click", function() {
  31.                 scope.$apply(function() {
  32.                     scope.message = "指令元素被点击";
  33.                 });
  34.             });
  35.         }
  36.     };
  37. });
  38. // 3. 解决jQuery和AngularJS的冲突
  39. // 确保在加载Angular之前加载jQuery
  40. // 然后Angular会自动使用jQuery而不是jQLite
  41. // 4. 在AngularJS服务中使用jQuery
  42. angular.module("myApp").service("myService", function($q) {
  43.     this.loadData = function() {
  44.         var deferred = $q.defer();
  45.         
  46.         // 使用jQuery的AJAX
  47.         $.ajax({
  48.             url: "/api/data",
  49.             success: function(data) {
  50.                 deferred.resolve(data);
  51.             },
  52.             error: function() {
  53.                 deferred.reject("加载数据失败");
  54.             }
  55.         });
  56.         
  57.         return deferred.promise;
  58.     };
  59. });
  60. // 在控制器中使用服务
  61. angular.module("myApp").controller("anotherController", function($scope, myService) {
  62.     myService.loadData().then(function(data) {
  63.         $scope.data = data;
  64.     }, function(error) {
  65.         $scope.error = error;
  66.     });
  67. });
复制代码

7.3 jQuery与React集成
  1. // 1. 在React组件中使用jQuery
  2. class MyComponent extends React.Component {
  3.     componentDidMount() {
  4.         // 在组件挂载后使用jQuery
  5.         $(this.refs.myElement).addClass("highlight");
  6.         
  7.         // 使用jQuery绑定事件
  8.         $(document).on("click", this.handleDocumentClick);
  9.     }
  10.    
  11.     componentWillUnmount() {
  12.         // 在组件卸载前清理jQuery事件
  13.         $(document).off("click", this.handleDocumentClick);
  14.     }
  15.    
  16.     handleDocumentClick = (e) => {
  17.         // 检查点击是否在组件外部
  18.         if (!$(this.refs.myElement).has(e.target).length) {
  19.             this.setState({ isOpen: false });
  20.         }
  21.     }
  22.    
  23.     render() {
  24.         return (
  25.             <div ref="myElement">
  26.                 {/* 组件内容 */}
  27.             </div>
  28.         );
  29.     }
  30. }
  31. // 2. 使用jQuery插件包装React组件
  32. class JqueryPluginWrapper extends React.Component {
  33.     componentDidMount() {
  34.         // 初始化jQuery插件
  35.         this.$element = $(this.refs.element);
  36.         this.$element.jqueryPluginName(this.props.options);
  37.     }
  38.    
  39.     componentDidUpdate(prevProps) {
  40.         // 如果props改变,更新插件
  41.         if (prevProps.options !== this.props.options) {
  42.             this.$element.jqueryPluginName("destroy");
  43.             this.$element.jqueryPluginName(this.props.options);
  44.         }
  45.     }
  46.    
  47.     componentWillUnmount() {
  48.         // 销毁插件
  49.         this.$element.jqueryPluginName("destroy");
  50.     }
  51.    
  52.     render() {
  53.         return <div ref="element">{this.props.children}</div>;
  54.     }
  55. }
  56. // 使用包装器
  57. function App() {
  58.     return (
  59.         <JqueryPluginWrapper options={{ speed: 500 }}>
  60.             <div>内容</div>
  61.         </JqueryPluginWrapper>
  62.     );
  63. }
  64. // 3. 使用React Portals和jQuery模态框
  65. class JqueryModal extends React.Component {
  66.     componentDidMount() {
  67.         // 创建模态框容器
  68.         this.modalContainer = document.createElement("div");
  69.         document.body.appendChild(this.modalContainer);
  70.         
  71.         // 使用jQuery初始化模态框
  72.         this.$modal = $(this.modalContainer);
  73.         this.$modal.html(this.props.children);
  74.         this.$modal.modal({
  75.             backdrop: "static",
  76.             keyboard: false,
  77.             show: true
  78.         });
  79.         
  80.         // 监听关闭事件
  81.         this.$modal.on("hidden.bs.modal", this.props.onClose);
  82.     }
  83.    
  84.     componentWillUnmount() {
  85.         // 销毁模态框
  86.         this.$modal.modal("hide");
  87.         this.$modal.off("hidden.bs.modal");
  88.         document.body.removeChild(this.modalContainer);
  89.     }
  90.    
  91.     render() {
  92.         return null; // React Portal不在这里渲染
  93.     }
  94. }
  95. // 使用模态框
  96. class App extends React.Component {
  97.     state = { showModal: false };
  98.    
  99.     openModal = () => {
  100.         this.setState({ showModal: true });
  101.     }
  102.    
  103.     closeModal = () => {
  104.         this.setState({ showModal: false });
  105.     }
  106.    
  107.     render() {
  108.         return (
  109.             <div>
  110.                 <button onClick={this.openModal}>打开模态框</button>
  111.                 {this.state.showModal && (
  112.                     <JqueryModal onClose={this.closeModal}>
  113.                         <div className="modal-dialog">
  114.                             <div className="modal-content">
  115.                                 <div className="modal-header">
  116.                                     <h4 className="modal-title">jQuery模态框</h4>
  117.                                 </div>
  118.                                 <div className="modal-body">
  119.                                     <p>这是一个使用jQuery和React的模态框</p>
  120.                                 </div>
  121.                                 <div className="modal-footer">
  122.                                     <button type="button" className="btn btn-default" data-dismiss="modal">关闭</button>
  123.                                 </div>
  124.                             </div>
  125.                         </div>
  126.                     </JqueryModal>
  127.                 )}
  128.             </div>
  129.         );
  130.     }
  131. }
复制代码

8. 总结

jQuery 1.11是一个功能强大且稳定的JavaScript库,它为开发者提供了简洁易用的API,使HTML文档遍历和操作、事件处理、动画和Ajax等任务变得更加简单。本手册全面覆盖了jQuery 1.11的各个方面,从基础的选择器、事件处理、DOM操作到高级的AJAX、动画和插件开发。

通过学习本手册,你应该已经掌握了:

1. jQuery的基本语法和核心概念
2. 各种选择器的使用方法和性能考虑
3. 事件处理机制和最佳实践
4. DOM操作的全面技术
5. AJAX请求的处理和错误处理
6. 动画效果的创建和控制
7. 插件开发的方法和模式
8. 常见问题的解决方案
9. 性能优化和最佳实践
10. 与其他库的集成技巧

在实际项目开发中,jQuery 1.11可以帮助你:

• 提高开发效率,减少代码量
• 解决跨浏览器兼容性问题
• 创建丰富的用户交互体验
• 简化复杂的DOM操作和事件处理
• 实现动态内容加载和表单验证
• 开发自定义插件扩展功能

尽管现代前端框架如React、Vue和Angular等已经成为主流,但jQuery仍然在许多现有项目和特定场景中发挥着重要作用。掌握jQuery 1.11的知识和技能,将使你能够更好地维护和开发基于jQuery的应用程序。

最后,记住学习是一个持续的过程。不断实践、探索和分享你的经验,你将能够更加熟练地使用jQuery 1.11,并在实际项目中发挥其最大的价值。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

频道订阅

频道订阅

加入社群

加入社群

联系我们|TG频道|RSS

Powered by Pixtech

© 2025 Pixtech Team.