|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
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
- <!-- 从jQuery CDN引入 -->
- <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
- <!-- 或者使用Google CDN -->
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
- <!-- 或者使用Microsoft CDN -->
- <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.11.3.min.js"></script>
复制代码
方式二:下载本地文件
- <!-- 下载到本地后引入 -->
- <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函数都应放在文档就绪处理函数中:
- $(document).ready(function(){
- // jQuery代码写在这里
- });
- // 简写形式
- $(function(){
- // jQuery代码写在这里
- });
复制代码
2.2 jQuery选择器
jQuery选择器允许您对HTML元素组或单个元素进行操作。jQuery选择器基于元素的id、类、类型、属性、属性值等”查找”(或选择)HTML元素。
- // 元素选择器
- $("p") // 选取所有<p>元素
- // ID选择器
- $("#test") // 选取id="test"的元素
- // 类选择器
- $(".test") // 选取所有class="test"的元素
- // 全局选择器
- $("*") // 选取所有元素
- // 多元素选择器
- $("p.intro") // 选取所有class="intro"的<p>元素
- $("p#demo") // 选取所有id="demo"的<p>元素
复制代码- // 后代选择器
- $("div p") // 选取<div>元素内的所有<p>元素
- // 子选择器
- $("div > p") // 选取<div>元素的所有直接子元素<p>
- // 相邻兄弟选择器
- $("div + p") // 选取<div>元素之后的下一个<p>元素
- // 一般兄弟选择器
- $("div ~ p") // 选取<div>元素之后的所有兄弟<p>元素
复制代码- // :first选择器
- $("p:first") // 选取第一个<p>元素
- // :last选择器
- $("p:last") // 选取最后一个<p>元素
- // :even选择器
- $("tr:even") // 选取所有偶数位置的<tr>元素
- // :odd选择器
- $("tr:odd") // 选取所有奇数位置的<tr>元素
- // :eq(index)选择器
- $("ul li:eq(3)") // 选取列表中的第四个元素(index从0开始)
- // :gt(index)选择器
- $("ul li:gt(3)") // 选取列表中index大于3的元素
- // :lt(index)选择器
- $("ul li:lt(3)") // 选取列表中index小于3的元素
- // :not(selector)选择器
- $("input:not(:empty)") // 选取所有不为空的input元素
复制代码- // [attribute]选择器
- $("[href]") // 选取所有带有href属性的元素
- // [attribute=value]选择器
- $("[href='#']") // 选取所有带有href属性且值等于"#"的元素
- // [attribute!=value]选择器
- $("[href!='#']") // 选取所有带有href属性且值不等于"#"的元素
- // [attribute$=value]选择器
- $("[href$='.jpg']") // 选取所有href属性值以".jpg"结尾的元素
- // [attribute^=value]选择器
- $("[href^='https']") // 选取所有href属性值以"https"开头的元素
- // [attribute*=value]选择器
- $("[href*='jquery']") // 选取所有href属性值包含"jquery"的元素
复制代码- // :input选择器
- $(":input") // 选取所有<input>, <textarea>, <select>和<button>元素
- // :text选择器
- $(":text") // 选取所有type="text"的<input>元素
- // :password选择器
- $(":password") // 选取所有type="password"的<input>元素
- // :radio选择器
- $(":radio") // 选取所有type="radio"的<input>元素
- // :checkbox选择器
- $(":checkbox") // 选取所有type="checkbox"的<input>元素
- // :submit选择器
- $(":submit") // 选取所有type="submit"的<input>元素
- // :reset选择器
- $(":reset") // 选取所有type="reset"的<input>元素
- // :button选择器
- $(":button") // 选取所有type="button"的<input>元素和<button>元素
- // :image选择器
- $(":image") // 选取所有type="image"的<input>元素
- // :file选择器
- $(":file") // 选取所有type="file"的<input>元素
- // :enabled选择器
- $(":enabled") // 选取所有启用的表单元素
- // :disabled选择器
- $(":disabled") // 选取所有禁用的表单元素
- // :selected选择器
- $(":selected") // 选取所有被选中的<option>元素
- // :checked选择器
- $(":checked") // 选取所有被选中的复选框和单选按钮
复制代码
2.3 jQuery事件处理
jQuery事件处理方法是jQuery中的核心功能之一。事件处理程序指的是当HTML中发生某些事件时所调用的方法。
- // click()方法
- $("p").click(function(){
- $(this).hide();
- });
- // dblclick()方法
- $("p").dblclick(function(){
- $(this).hide();
- });
- // mouseenter()方法
- $("#p1").mouseenter(function(){
- alert("您进入了 p1!");
- });
- // mouseleave()方法
- $("#p1").mouseleave(function(){
- alert("再见,您离开了 p1!");
- });
- // mousedown()方法
- $("#p1").mousedown(function(){
- alert("鼠标在该段落上按下!");
- });
- // mouseup()方法
- $("#p1").mouseup(function(){
- alert("鼠标在段落上松开!");
- });
- // hover()方法
- $("#p1").hover(
- function(){
- alert("你进入了 p1!");
- },
- function(){
- alert("再见,你现在离开了 p1!");
- }
- );
- // focus()方法
- $("input").focus(function(){
- $(this).css("background-color","#cccccc");
- });
- // blur()方法
- $("input").blur(function(){
- $(this).css("background-color","#ffffff");
- });
复制代码
on()方法是jQuery 1.7版本引入的,用于绑定事件处理程序,提供了比bind()、live()和delegate()方法更灵活的功能。
- // 基本用法
- $("p").on("click", function(){
- $(this).hide();
- });
- // 绑定多个事件
- $("p").on({
- mouseenter: function(){
- $(this).css("background-color", "lightgray");
- },
- mouseleave: function(){
- $(this).css("background-color", "white");
- },
- click: function(){
- $(this).css("background-color", "yellow");
- }
- });
- // 事件委托
- $(document).on("click", "p", function(){
- $(this).hide();
- });
复制代码
当事件被触发时,事件对象(event object)会被传递给事件处理函数:
- $("p").click(function(event){
- // 阻止默认行为
- event.preventDefault();
-
- // 阻止事件冒泡
- event.stopPropagation();
-
- // 获取事件类型
- alert(event.type); // "click"
-
- // 获取触发事件的元素
- alert(event.target);
-
- // 获取页面X坐标
- alert(event.pageX);
-
- // 获取页面Y坐标
- alert(event.pageY);
- });
复制代码
jQuery允许你创建自定义事件:
- // 绑定自定义事件
- $("p").on("myCustomEvent", function(event, myName, myValue){
- $(this).text(myName + ", 你好! " + myValue);
- });
- // 触发自定义事件
- $("button").click(function(){
- $("p").trigger("myCustomEvent", ["John", "工程师"]);
- });
复制代码
2.4 jQuery DOM操作
jQuery提供了多种方法来操作DOM元素,包括获取和设置内容、属性、样式等。
- // text() - 设置或返回所选元素的文本内容
- $("#test").text(); // 获取文本内容
- $("#test").text("Hello world!"); // 设置文本内容
- // html() - 设置或返回所选元素的内容(包括HTML标记)
- $("#test").html(); // 获取内容
- $("#test").html("<b>Hello world!</b>"); // 设置内容
- // val() - 设置或返回表单字段的值
- $("#test").val(); // 获取值
- $("#test").val("John Doe"); // 设置值
复制代码- // attr() - 设置或返回属性值
- $("#w3s").attr("href"); // 获取href属性值
- $("#w3s").attr("href", "https://www.w3schools.com/jquery/"); // 设置href属性值
- // 同时设置多个属性
- $("#w3s").attr({
- "href" : "https://www.w3schools.com/jquery/",
- "title" : "jQuery Tutorial"
- });
- // prop() - 设置或返回属性值(适用于checked、selected、disabled等属性)
- $("#checkbox1").prop("checked"); // 获取checked属性
- $("#checkbox1").prop("checked", true); // 设置checked属性
- // removeAttr() - 移除属性
- $("#w3s").removeAttr("title");
复制代码- // append() - 在被选元素的结尾插入内容
- $("p").append("Some appended text.");
- // prepend() - 在被选元素的开头插入内容
- $("p").prepend("Some prepended text.");
- // after() - 在被选元素之后插入内容
- $("img").after("Some text after");
- // before() - 在被选元素之前插入内容
- $("img").before("Some text before");
复制代码- // remove() - 删除被选元素(及其子元素)
- $("#div1").remove();
- // empty() - 从被选元素中删除子元素
- $("#div1").empty();
- // remove()方法可接受一个参数,允许您对被删元素进行过滤
- $("p").remove(".italic"); // 删除所有class="italic"的<p>元素
复制代码- // addClass() - 向被选元素添加一个或多个类
- $("h1, h2, p").addClass("blue");
- $("div").addClass("important blue");
- // removeClass() - 从被选元素删除一个或多个类
- $("h1, h2, p").removeClass("blue");
- // toggleClass() - 对被选元素进行添加/删除类的切换操作
- $("h1, h2, p").toggleClass("blue");
- // hasClass() - 检查被选元素是否包含指定的类
- $("h1").hasClass("blue"); // 返回true或false
复制代码- // css() - 设置或返回样式属性
- $("p").css("background-color"); // 返回背景颜色
- $("p").css("background-color", "yellow"); // 设置背景颜色
- // 设置多个CSS属性
- $("p").css({
- "background-color": "yellow",
- "font-size": "200%"
- });
- // 尺寸相关方法
- // width()和height()方法
- $("#div1").width(); // 返回宽度
- $("#div1").width(500); // 设置宽度
- $("#div1").height(); // 返回高度
- $("#div1").height(500); // 设置高度
- // innerWidth()和innerHeight()方法
- $("#div1").innerWidth(); // 返回宽度(包括内边距)
- $("#div1").innerHeight(); // 返回高度(包括内边距)
- // outerWidth()和outerHeight()方法
- $("#div1").outerWidth(); // 返回宽度(包括内边距和边框)
- $("#div1").outerHeight(); // 返回高度(包括内边距和边框)
- $("#div1").outerWidth(true); // 返回宽度(包括内边距、边框和外边距)
- $("#div1").outerHeight(true); // 返回高度(包括内边距、边框和外边距)
复制代码- // parent() - 返回被选元素的直接父元素
- $("span").parent();
- // parents() - 返回被选元素的所有祖先元素
- $("span").parents();
- // parentsUntil() - 返回介于两个给定元素之间的所有祖先元素
- $("span").parentsUntil("div");
- // children() - 返回被选元素的所有直接子元素
- $("div").children();
- // find() - 返回被选元素的后代元素
- $("div").find("span");
- // siblings() - 返回被选元素的所有同胞元素
- $("h2").siblings();
- // next() - 返回被选元素的下一个同胞元素
- $("h2").next();
- // nextAll() - 返回被选元素的所有跟随的同胞元素
- $("h2").nextAll();
- // nextUntil() - 返回介于两个给定参数之间的所有跟随的同胞元素
- $("h2").nextUntil("h6");
- // prev(), prevAll()和prevUntil()方法的工作方式与上面的方法类似,只不过方向相反
- // first() - 返回被选元素的首个元素
- $("div p").first();
- // last() - 返回被选元素的最后一个元素
- $("div p").last();
- // eq() - 返回被选元素中带有指定索引号的元素
- $("p").eq(1);
- // filter() - 允许您规定一个标准。不匹配这个标准的元素会被从集合中删除,匹配的元素会被返回
- $("p").filter(".intro");
- // not() - 返回不匹配标准的所有元素
- $("p").not(".intro");
复制代码
3. jQuery高级特性
3.1 jQuery AJAX
AJAX是与服务器交换数据的技术,它在不重载全部页面的情况下,实现了对部分网页的更新。
- // load()方法 - 从服务器加载数据,并把返回的数据放入被选元素中
- $("#div1").load("demo_test.txt"); // 加载文件内容
- $("#div1").load("demo_test.txt #p1"); // 加载文件中id="p1"的元素
- // $.get()方法 - 通过HTTP GET请求从服务器上请求数据
- $.get("demo_test.php", function(data, status){
- alert("数据: " + data + "\n状态: " + status);
- });
- // $.post()方法 - 通过HTTP POST请求从服务器上请求数据
- $.post("demo_test_post.php",
- {
- name: "John",
- city: "Boston"
- },
- function(data, status){
- alert("数据: " + data + "\n状态: " + status);
- }
- );
- // $.ajax()方法 - 执行异步HTTP(Ajax)请求
- $.ajax({
- url: "test.html",
- context: document.body,
- success: function(){
- $(this).addClass("done");
- }
- });
- // 更复杂的$.ajax()示例
- $.ajax({
- type: "POST",
- url: "some.php",
- data: { name: "John", location: "Boston" },
- dataType: "json",
- success: function(data){
- // 处理返回的数据
- },
- error: function(xhr, status, error){
- // 处理错误
- },
- complete: function(xhr, status){
- // 请求完成后调用的函数
- }
- });
复制代码
jQuery提供了一组用于AJAX事件的全局事件处理程序:
- // ajaxStart() - 在AJAX请求开始前执行
- $(document).ajaxStart(function(){
- $(this).html("<img src='demo_wait.gif' />");
- });
- // ajaxSend() - 在AJAX请求发送前执行
- $(document).ajaxSend(function(event, xhr, options){
- $(this).html("正在发送请求...");
- });
- // ajaxSuccess() - 在AJAX请求成功时执行
- $(document).ajaxSuccess(function(event, xhr, options){
- $(this).html("请求成功!");
- });
- // ajaxError() - 在AJAX请求失败时执行
- $(document).ajaxError(function(event, xhr, options, exc){
- $(this).html("请求出错:" + xhr.statusText);
- });
- // ajaxComplete() - 在AJAX请求完成时执行(无论成功或失败)
- $(document).ajaxComplete(function(event, xhr, options){
- $(this).html("请求完成");
- });
- // ajaxStop() - 在所有AJAX请求完成后执行
- $(document).ajaxStop(function(){
- $(this).html("所有请求完成");
- });
复制代码
3.2 jQuery动画
jQuery提供了一组用于创建自定义动画的函数。
- // hide()和show()方法
- $("#hide").click(function(){
- $("p").hide();
- });
- $("#show").click(function(){
- $("p").show();
- });
- // toggle()方法
- $("button").click(function(){
- $("p").toggle();
- });
- // 可以使用speed参数控制速度
- $("button").click(function(){
- $("p").toggle(1000); // 1000毫秒
- });
- // 可以使用callback参数在动画完成后执行函数
- $("button").click(function(){
- $("p").toggle(1000, function(){
- alert("动画完成");
- });
- });
复制代码- // fadeIn()方法
- $("button").click(function(){
- $("#div1").fadeIn();
- $("#div2").fadeIn("slow");
- $("#div3").fadeIn(3000);
- });
- // fadeOut()方法
- $("button").click(function(){
- $("#div1").fadeOut();
- $("#div2").fadeOut("slow");
- $("#div3").fadeOut(3000);
- });
- // fadeToggle()方法
- $("button").click(function(){
- $("#div1").fadeToggle();
- $("#div2").fadeToggle("slow");
- $("#div3").fadeToggle(3000);
- });
- // fadeTo()方法 - 允许渐变为给定的不透明度(值介于0与1之间)
- $("button").click(function(){
- $("#div1").fadeTo("slow", 0.15);
- $("#div2").fadeTo("slow", 0.4);
- $("#div3").fadeTo("slow", 0.7);
- });
复制代码- // slideDown()方法
- $("#flip").click(function(){
- $("#panel").slideDown();
- });
- // slideUp()方法
- $("#flip").click(function(){
- $("#panel").slideUp();
- });
- // slideToggle()方法
- $("#flip").click(function(){
- $("#panel").slideToggle();
- });
复制代码- // animate()方法 - 创建自定义动画
- $("button").click(function(){
- $("div").animate({left: '250px'});
- });
- // 操作多个属性
- $("button").click(function(){
- $("div").animate({
- left: '250px',
- opacity: '0.5',
- height: '150px',
- width: '150px'
- });
- });
- // 使用相对值
- $("button").click(function(){
- $("div").animate({
- left: '250px',
- height: '+=150px',
- width: '+=150px'
- });
- });
- // 使用预定义的值
- $("button").click(function(){
- $("div").animate({
- height: 'toggle'
- });
- });
- // 使用队列功能
- $("button").click(function(){
- var div = $("div");
- div.animate({height: '300px', opacity: '0.4'}, "slow");
- div.animate({width: '300px', opacity: '0.8'}, "slow");
- div.animate({height: '100px', opacity: '0.4'}, "slow");
- div.animate({width: '100px', opacity: '0.8'}, "slow");
- });
- // 停止动画
- $("#stop").click(function(){
- $("#panel").stop();
- });
复制代码
3.3 jQuery插件开发
jQuery插件是扩展jQuery功能的一种方式,可以让您创建可重用的代码。
- // 创建一个简单的插件
- (function($) {
- $.fn.greenify = function() {
- this.css("color", "green");
- return this; // 支持链式调用
- };
- }(jQuery));
- // 使用插件
- $("a").greenify().addClass("greenified");
复制代码- (function($) {
- $.fn.greenify = function(options) {
- // 设置默认值
- var settings = $.extend({
- color: "#556b2f",
- backgroundColor: "white"
- }, options);
-
- // 应用设置
- return this.css({
- color: settings.color,
- backgroundColor: settings.backgroundColor
- });
- };
- }(jQuery));
- // 使用带选项的插件
- $("div").greenify({
- color: "orange"
- });
复制代码- (function($) {
- var methods = {
- init: function(options) {
- // 初始化代码
- },
- show: function() {
- // 显示代码
- },
- hide: function() {
- // 隐藏代码
- },
- update: function(content) {
- // 更新代码
- }
- };
-
- $.fn.tooltip = function(method) {
- // 方法调用
- if (methods[method]) {
- return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
- } else if (typeof method === 'object' || !method) {
- return methods.init.apply(this, arguments);
- } else {
- $.error('Method ' + method + ' does not exist on jQuery.tooltip');
- }
- };
- }(jQuery));
- // 使用带方法的插件
- $('div').tooltip(); // 初始化
- $('div').tooltip('show'); // 调用show方法
- $('div').tooltip('hide'); // 调用hide方法
- $('div').tooltip('update', '新内容'); // 调用update方法
复制代码
4. 实例教程
4.1 表单验证实例
- $(document).ready(function() {
- // 表单验证
- $("#myForm").submit(function(event) {
- var isValid = true;
-
- // 验证用户名
- var username = $("#username").val();
- if (username.length < 3) {
- $("#usernameError").text("用户名必须至少3个字符");
- isValid = false;
- } else {
- $("#usernameError").text("");
- }
-
- // 验证邮箱
- var email = $("#email").val();
- var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
- if (!emailRegex.test(email)) {
- $("#emailError").text("请输入有效的邮箱地址");
- isValid = false;
- } else {
- $("#emailError").text("");
- }
-
- // 验证密码
- var password = $("#password").val();
- if (password.length < 6) {
- $("#passwordError").text("密码必须至少6个字符");
- isValid = false;
- } else {
- $("#passwordError").text("");
- }
-
- // 验证确认密码
- var confirmPassword = $("#confirmPassword").val();
- if (password !== confirmPassword) {
- $("#confirmPasswordError").text("两次输入的密码不匹配");
- isValid = false;
- } else {
- $("#confirmPasswordError").text("");
- }
-
- // 如果表单无效,阻止提交
- if (!isValid) {
- event.preventDefault();
- }
- });
-
- // 实时验证
- $("#username").on("input", function() {
- var username = $(this).val();
- if (username.length < 3) {
- $("#usernameError").text("用户名必须至少3个字符");
- } else {
- $("#usernameError").text("");
- }
- });
-
- $("#email").on("input", function() {
- var email = $(this).val();
- var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
- if (!emailRegex.test(email)) {
- $("#emailError").text("请输入有效的邮箱地址");
- } else {
- $("#emailError").text("");
- }
- });
-
- $("#password").on("input", function() {
- var password = $(this).val();
- if (password.length < 6) {
- $("#passwordError").text("密码必须至少6个字符");
- } else {
- $("#passwordError").text("");
- }
-
- // 检查确认密码
- var confirmPassword = $("#confirmPassword").val();
- if (confirmPassword && password !== confirmPassword) {
- $("#confirmPasswordError").text("两次输入的密码不匹配");
- } else {
- $("#confirmPasswordError").text("");
- }
- });
-
- $("#confirmPassword").on("input", function() {
- var confirmPassword = $(this).val();
- var password = $("#password").val();
- if (password !== confirmPassword) {
- $("#confirmPasswordError").text("两次输入的密码不匹配");
- } else {
- $("#confirmPasswordError").text("");
- }
- });
- });
复制代码
4.2 图片轮播实例
4.3 AJAX加载内容实例
- $(document).ready(function() {
- // 加载文章列表
- function loadArticles(page) {
- // 显示加载指示器
- $("#loading").show();
-
- // 发送AJAX请求
- $.ajax({
- url: "get_articles.php",
- type: "GET",
- data: { page: page },
- dataType: "json",
- success: function(response) {
- // 隐藏加载指示器
- $("#loading").hide();
-
- // 清空当前文章列表
- $("#articles").empty();
-
- // 添加新文章
- if (response.articles.length > 0) {
- $.each(response.articles, function(index, article) {
- var articleHtml = '<div class="article">';
- articleHtml += '<h2>' + article.title + '</h2>';
- articleHtml += '<div class="meta">发布于 ' + article.date + ' 作者:' + article.author + '</div>';
- articleHtml += '<div class="content">' + article.content + '</div>';
- articleHtml += '<div class="actions">';
- articleHtml += '<button class="read-more" data-id="' + article.id + '">阅读更多</button>';
- articleHtml += '<button class="like" data-id="' + article.id + '">点赞 (' + article.likes + ')</button>';
- articleHtml += '</div>';
- articleHtml += '</div>';
-
- $("#articles").append(articleHtml);
- });
-
- // 更新分页
- updatePagination(response.currentPage, response.totalPages);
- } else {
- $("#articles").html("<p>没有找到文章。</p>");
- }
- },
- error: function(xhr, status, error) {
- // 隐藏加载指示器
- $("#loading").hide();
-
- // 显示错误信息
- $("#articles").html("<p>加载文章时出错: " + error + "</p>");
- }
- });
- }
-
- // 更新分页
- function updatePagination(currentPage, totalPages) {
- $("#pagination").empty();
-
- // 上一页按钮
- if (currentPage > 1) {
- $("#pagination").append('<button class="page-btn" data-page="' + (currentPage - 1) + '">上一页</button>');
- }
-
- // 页码按钮
- for (var i = 1; i <= totalPages; i++) {
- if (i === currentPage) {
- $("#pagination").append('<button class="page-btn active" data-page="' + i + '">' + i + '</button>');
- } else {
- $("#pagination").append('<button class="page-btn" data-page="' + i + '">' + i + '</button>');
- }
- }
-
- // 下一页按钮
- if (currentPage < totalPages) {
- $("#pagination").append('<button class="page-btn" data-page="' + (currentPage + 1) + '">下一页</button>');
- }
- }
-
- // 加载第一页
- loadArticles(1);
-
- // 分页按钮点击事件
- $(document).on("click", ".page-btn", function() {
- var page = $(this).data("page");
- loadArticles(page);
-
- // 滚动到顶部
- $("html, body").animate({ scrollTop: 0 }, "slow");
- });
-
- // 阅读更多按钮点击事件
- $(document).on("click", ".read-more", function() {
- var articleId = $(this).data("id");
-
- // 显示加载指示器
- $("#loading").show();
-
- // 发送AJAX请求获取完整文章
- $.ajax({
- url: "get_article.php",
- type: "GET",
- data: { id: articleId },
- dataType: "json",
- success: function(response) {
- // 隐藏加载指示器
- $("#loading").hide();
-
- // 显示文章详情模态框
- $("#modal-title").text(response.title);
- $("#modal-content").html(response.fullContent);
- $("#modal-meta").text("发布于 " + response.date + " 作者:" + response.author);
- $("#article-modal").show();
- },
- error: function(xhr, status, error) {
- // 隐藏加载指示器
- $("#loading").hide();
-
- // 显示错误信息
- alert("加载文章详情时出错: " + error);
- }
- });
- });
-
- // 点赞按钮点击事件
- $(document).on("click", ".like", function() {
- var button = $(this);
- var articleId = button.data("id");
-
- // 发送AJAX请求点赞
- $.ajax({
- url: "like_article.php",
- type: "POST",
- data: { id: articleId },
- dataType: "json",
- success: function(response) {
- if (response.success) {
- // 更新点赞数
- button.text("点赞 (" + response.likes + ")");
-
- // 添加点赞动画效果
- button.addClass("liked");
- setTimeout(function() {
- button.removeClass("liked");
- }, 1000);
- } else {
- alert(response.message);
- }
- },
- error: function(xhr, status, error) {
- alert("点赞时出错: " + error);
- }
- });
- });
-
- // 关闭模态框
- $(".close-modal").click(function() {
- $("#article-modal").hide();
- });
-
- // 点击模态框外部关闭模态框
- $(window).click(function(event) {
- if ($(event.target).is("#article-modal")) {
- $("#article-modal").hide();
- }
- });
- });
复制代码
4.4 拖放功能实例
- $(document).ready(function() {
- // 使元素可拖动
- $(".draggable").draggable({
- revert: "invalid", // 如果不被接受,则返回原位置
- cursor: "move",
- start: function(event, ui) {
- // 拖动开始时的操作
- $(this).css("opacity", "0.7");
- },
- stop: function(event, ui) {
- // 拖动结束时的操作
- $(this).css("opacity", "1");
- }
- });
-
- // 设置放置区域
- $(".droppable").droppable({
- accept: ".draggable", // 接受的元素
- hoverClass: "droppable-hover", // 悬停时的样式
- drop: function(event, ui) {
- // 放置时的操作
- var draggedItem = ui.draggable;
- var droppedIn = $(this);
-
- // 复制拖动的元素到放置区域
- var clone = draggedItem.clone();
- clone.draggable({
- revert: "invalid",
- cursor: "move"
- });
-
- droppedIn.append(clone);
-
- // 添加放置效果
- droppedIn.addClass("dropped");
- setTimeout(function() {
- droppedIn.removeClass("dropped");
- }, 500);
-
- // 更新计数
- updateCounts();
- },
- out: function(event, ui) {
- // 离开放置区域时的操作
- $(this).removeClass("droppable-hover");
- }
- });
-
- // 更新计数函数
- function updateCounts() {
- // 更新源区域的计数
- $("#source-count").text($("#source .draggable").length);
-
- // 更新目标区域的计数
- $("#target-count").text($("#target .draggable").length);
- }
-
- // 初始化计数
- updateCounts();
-
- // 添加重置按钮功能
- $("#reset").click(function() {
- // 清空目标区域
- $("#target").empty();
-
- // 重置源区域
- $("#source").html(
- '<div class="draggable" id="item1">项目 1</div>' +
- '<div class="draggable" id="item2">项目 2</div>' +
- '<div class="draggable" id="item3">项目 3</div>' +
- '<div class="draggable" id="item4">项目 4</div>' +
- '<div class="draggable" id="item5">项目 5</div>'
- );
-
- // 重新使元素可拖动
- $(".draggable").draggable({
- revert: "invalid",
- cursor: "move",
- start: function(event, ui) {
- $(this).css("opacity", "0.7");
- },
- stop: function(event, ui) {
- $(this).css("opacity", "1");
- }
- });
-
- // 更新计数
- updateCounts();
- });
-
- // 添加排序功能
- $("#source, #target").sortable({
- connectWith: ".connected-sortable", // 连接可排序区域
- placeholder: "sortable-placeholder", // 占位符样式
- tolerance: "pointer", // 指定用于测试项目是否在另一项目上的模式
- cursor: "move",
- opacity: 0.7,
- update: function(event, ui) {
- // 排序更新时的操作
- updateCounts();
- }
- }).disableSelection(); // 防止文本选择
- });
复制代码
5. 常见问题解答
5.1 jQuery与其他库冲突问题
问题:当我在同一页面使用jQuery和其他JavaScript库(如Prototype、MooTools等)时,出现冲突,导致代码无法正常工作。
解决方案:
jQuery使用$作为其别名,但其他库也可能使用$符号。为了解决冲突,jQuery提供了noConflict()方法:
- // 方法1:完全放弃$控制权
- jQuery.noConflict();
- // 现在可以使用jQuery代替$
- jQuery(document).ready(function(){
- jQuery("p").text("Hello, world!");
- });
- // 方法2:自定义别名
- var jq = jQuery.noConflict();
- // 使用jq作为jQuery的别名
- jq(document).ready(function(){
- jq("p").text("Hello, world!");
- });
- // 方法3:在内部使用$
- jQuery.noConflict();
- jQuery(document).ready(function($) {
- // 在这个函数内部,$仍然指向jQuery
- $("p").text("Hello, world!");
- });
- // 方法4:使用立即执行函数表达式(IIFE)
- jQuery.noConflict();
- (function($) {
- $(function() {
- // $在这里指向jQuery
- $("p").text("Hello, world!");
- });
- })(jQuery);
复制代码
5.2 jQuery选择器性能问题
问题:我的页面中有大量元素,使用jQuery选择器时性能很差,页面响应缓慢。
解决方案:
优化jQuery选择器性能的几种方法:
- // 1. 使用ID选择器
- // 快速
- $("#myId");
- // 慢速
- $("div#myId");
- // 2. 缓存选择器结果
- // 不好的做法
- for (var i = 0; i < 100; i++) {
- $("#myElement").append(i);
- }
- // 好的做法
- var myElement = $("#myElement");
- for (var i = 0; i < 100; i++) {
- myElement.append(i);
- }
- // 3. 使用find()代替上下文选择器
- // 不好的做法
- $("div", "#myContainer");
- // 好的做法
- $("#myContainer").find("div");
- // 4. 避免通用选择器
- // 不好的做法
- $(".container > *");
- // 好的做法
- $(".container").children();
- // 5. 使用更具体的选择器
- // 不好的做法
- $("div.data");
- // 好的做法
- $("div.data-table");
- // 6. 使用原生DOM方法获取元素,然后传递给jQuery
- // 不好的做法
- $("#myId .myClass");
- // 好的做法
- var element = document.getElementById("myId");
- var myElements = $(element).find(".myClass");
复制代码
5.3 AJAX请求缓存问题
问题:在IE浏览器中,我的AJAX请求被缓存,导致我获取不到最新的数据。
解决方案:
- // 方法1:禁用AJAX缓存(全局设置)
- $.ajaxSetup({
- cache: false
- });
- // 方法2:在单个AJAX请求中禁用缓存
- $.ajax({
- url: "myurl.php",
- cache: false,
- success: function(data) {
- // 处理数据
- }
- });
- // 方法3:在URL中添加时间戳或随机数
- $.ajax({
- url: "myurl.php?t=" + new Date().getTime(),
- success: function(data) {
- // 处理数据
- }
- });
- // 方法4:使用POST方法代替GET方法
- $.ajax({
- type: "POST",
- url: "myurl.php",
- success: function(data) {
- // 处理数据
- }
- });
复制代码
5.4 事件委托问题
问题:我动态添加了元素到页面中,但是这些元素上的事件处理程序不起作用。
解决方案:
使用事件委托(Event Delegation)来处理动态添加的元素:
- // 不好的做法 - 直接绑定事件
- $(".myButton").click(function() {
- alert("按钮被点击");
- });
- // 动态添加按钮
- $("#container").append("<button class='myButton'>新按钮</button>");
- // 这个新按钮不会响应点击事件
- // 好的做法 - 使用事件委托
- $("#container").on("click", ".myButton", function() {
- alert("按钮被点击");
- });
- // 动态添加按钮
- $("#container").append("<button class='myButton'>新按钮</button>");
- // 这个新按钮会响应点击事件
- // 对于jQuery 1.11,也可以使用delegate()方法
- $("#container").delegate(".myButton", "click", function() {
- alert("按钮被点击");
- });
复制代码
5.5 动画队列问题
问题:当用户快速多次触发动画时,动画效果会排队执行,导致动画效果与用户操作不同步。
解决方案:
- // 不好的做法
- $("#myElement").hover(
- function() {
- $(this).animate({height: "200px"}, 500);
- },
- function() {
- $(this).animate({height: "100px"}, 500);
- }
- );
- // 好的做法 - 使用stop()方法
- $("#myElement").hover(
- function() {
- $(this).stop().animate({height: "200px"}, 500);
- },
- function() {
- $(this).stop().animate({height: "100px"}, 500);
- }
- );
- // 更好的做法 - 使用stop(true, true)
- $("#myElement").hover(
- function() {
- $(this).stop(true, true).animate({height: "200px"}, 500);
- },
- function() {
- $(this).stop(true, true).animate({height: "100px"}, 500);
- }
- );
- // 或者使用finish()方法(jQuery 1.9+)
- $("#myElement").hover(
- function() {
- $(this).finish().animate({height: "200px"}, 500);
- },
- function() {
- $(this).finish().animate({height: "100px"}, 500);
- }
- );
复制代码
5.6 内存泄漏问题
问题:我的单页应用在使用一段时间后变得越来越慢,内存使用量不断增加。
解决方案:
- // 1. 解除不再需要的事件绑定
- function setupEvents() {
- $("#myButton").on("click", handleClick);
- }
- function cleanupEvents() {
- $("#myButton").off("click", handleClick);
- }
- // 2. 在移除元素前解除事件绑定
- $("#myElement").remove(); // 这会自动解除事件绑定
- // 或者
- $("#myElement").empty(); // 这会解除所有子元素的事件绑定
- // 3. 使用命名空间事件,便于批量解除
- $("#myElement").on("click.myNamespace", function() {
- // 处理点击事件
- });
- // 解除特定命名空间的所有事件
- $("#myElement").off(".myNamespace");
- // 4. 避免在循环中创建闭包
- // 不好的做法
- for (var i = 0; i < 10; i++) {
- $("#myElement" + i).click(function() {
- alert("元素 " + i + " 被点击"); // 这总是显示10
- });
- }
- // 好的做法
- for (var i = 0; i < 10; i++) {
- (function(index) {
- $("#myElement" + index).click(function() {
- alert("元素 " + index + " 被点击");
- });
- })(i);
- }
- // 5. 使用data()方法存储数据而不是DOM属性
- // 不好的做法
- $("#myElement").attr("data-mydata", JSON.stringify(largeObject));
- // 好的做法
- $("#myElement").data("mydata", largeObject);
- // 6. 在不再需要时清除数据
- $("#myElement").removeData("mydata");
复制代码
5.7 跨域请求问题
问题:当我尝试从不同的域获取数据时,浏览器阻止了我的AJAX请求。
解决方案:
- // 方法1:使用JSONP
- $.ajax({
- url: "https://example.com/data",
- dataType: "jsonp",
- success: function(data) {
- // 处理数据
- }
- });
- // 方法2:使用CORS(需要服务器支持)
- $.ajax({
- url: "https://example.com/data",
- xhrFields: {
- withCredentials: true
- },
- crossDomain: true,
- success: function(data) {
- // 处理数据
- }
- });
- // 方法3:使用服务器代理
- // 在同域的服务器上创建一个代理脚本,然后通过该脚本请求跨域数据
- $.ajax({
- url: "/proxy.php?url=" + encodeURIComponent("https://example.com/data"),
- success: function(data) {
- // 处理数据
- }
- });
- // proxy.php示例代码
- /*
- <?php
- $url = $_GET['url'];
- echo file_get_contents($url);
- ?>
- */
复制代码
6. 最佳实践和性能优化
6.1 代码组织最佳实践
- // 1. 使用立即执行函数表达式(IIFE)避免全局变量污染
- (function($) {
- // 你的jQuery代码在这里
-
- // 定义私有变量和函数
- var privateVar = "I'm private";
-
- function privateFunction() {
- // 私有函数实现
- }
-
- // 定义公共API
- $.fn.myPlugin = function(options) {
- // 插件实现
- };
-
- })(jQuery);
- // 2. 使用对象字面量组织代码
- var myApp = {
- settings: {
- apiUrl: "https://api.example.com",
- timeout: 5000
- },
-
- init: function() {
- this.cacheDom();
- this.bindEvents();
- this.loadData();
- },
-
- cacheDom: function() {
- this.$container = $("#container");
- this.$button = $("#button");
- },
-
- bindEvents: function() {
- var self = this;
- this.$button.on("click", function() {
- self.handleButtonClick();
- });
- },
-
- handleButtonClick: function() {
- // 处理按钮点击
- },
-
- loadData: function() {
- var self = this;
- $.ajax({
- url: this.settings.apiUrl,
- timeout: this.settings.timeout,
- success: function(data) {
- self.processData(data);
- },
- error: function() {
- self.handleError();
- }
- });
- },
-
- processData: function(data) {
- // 处理数据
- },
-
- handleError: function() {
- // 处理错误
- }
- };
- // 初始化应用
- $(document).ready(function() {
- myApp.init();
- });
- // 3. 使用模块模式
- var Module = (function($) {
- // 私有变量
- var privateVar = "I'm private";
-
- // 私有函数
- function privateFunction() {
- return privateVar;
- }
-
- // 返回公共API
- return {
- publicVar: "I'm public",
- publicFunction: function() {
- return privateFunction();
- }
- };
- })(jQuery);
- // 使用模块
- console.log(Module.publicVar); // "I'm public"
- console.log(Module.publicFunction()); // "I'm private"
- console.log(Module.privateVar); // undefined
- console.log(Module.privateFunction()); // TypeError
复制代码
6.2 性能优化技巧
6.3 错误处理和调试
- // 1. 全局AJAX错误处理
- $(document).ajaxError(function(event, jqXHR, settings, thrownError) {
- console.error("AJAX错误:", thrownError);
- console.error("URL:", settings.url);
- console.error("状态:", jqXHR.status);
- console.error("响应文本:", jqXHR.responseText);
-
- // 显示用户友好的错误消息
- showError("发生了一个错误,请稍后再试。");
- });
- // 2. 封装AJAX调用以便统一处理错误
- function safeAjax(options) {
- var defaultOptions = {
- error: function(jqXHR, textStatus, errorThrown) {
- console.error("AJAX错误:", textStatus, errorThrown);
- showError("请求失败,请稍后再试。");
- },
- timeout: 10000 // 10秒超时
- };
-
- return $.ajax($.extend({}, defaultOptions, options));
- }
- // 使用封装的AJAX函数
- safeAjax({
- url: "/api/data",
- success: function(data) {
- processData(data);
- }
- });
- // 3. 使用try-catch处理可能的错误
- function riskyOperation() {
- try {
- // 可能出错的代码
- var result = potentiallyRiskyFunction();
- return result;
- } catch (error) {
- console.error("操作失败:", error);
- showError("操作失败,请稍后再试。");
- return null;
- }
- }
- // 4. 使用jQuery的deferred对象处理异步操作
- function fetchData() {
- var deferred = $.Deferred();
-
- $.ajax({
- url: "/api/data",
- success: function(data) {
- deferred.resolve(data);
- },
- error: function() {
- deferred.reject("获取数据失败");
- }
- });
-
- return deferred.promise();
- }
- // 使用deferred对象
- fetchData().done(function(data) {
- processData(data);
- }).fail(function(error) {
- showError(error);
- });
- // 5. 使用console.log进行调试
- function debugLog(message) {
- if (window.console && window.console.log) {
- console.log(message);
- }
- }
- // 6. 使用jQuery的data方法存储调试信息
- $("#myElement").data("debug", {
- created: new Date(),
- createdBy: "John Doe",
- purpose: "Example element"
- });
- // 检索调试信息
- var debugInfo = $("#myElement").data("debug");
- console.log(debugInfo);
复制代码
7. jQuery与其他库的集成
7.1 jQuery与Bootstrap集成
- // 1. 使用Bootstrap的模态框
- $(document).ready(function() {
- // 显示模态框
- $("#showModalBtn").click(function() {
- $("#myModal").modal("show");
- });
-
- // 隐藏模态框
- $("#hideModalBtn").click(function() {
- $("#myModal").modal("hide");
- });
-
- // 监听模态框事件
- $("#myModal").on("show.bs.modal", function(e) {
- console.log("模态框即将显示");
- });
-
- $("#myModal").on("shown.bs.modal", function(e) {
- console.log("模态框已显示");
- });
-
- $("#myModal").on("hide.bs.modal", function(e) {
- console.log("模态框即将隐藏");
- });
-
- $("#myModal").on("hidden.bs.modal", function(e) {
- console.log("模态框已隐藏");
- });
- });
- // 2. 使用Bootstrap的标签页
- $(document).ready(function() {
- // 监听标签页切换事件
- $('a[data-toggle="tab"]').on("shown.bs.tab", function(e) {
- var target = $(e.target).attr("href"); // 激活的标签页
- var previous = $(e.relatedTarget).attr("href"); // 上一个标签页
-
- console.log("切换到: " + target);
- console.log("上一个: " + previous);
- });
-
- // 通过JavaScript激活标签页
- $("#activateTabBtn").click(function() {
- $('#myTabs a[href="#profile"]').tab("show");
- });
- });
- // 3. 使用Bootstrap的警告框
- $(document).ready(function() {
- // 关闭警告框
- $(".alert").alert();
-
- // 监听关闭事件
- $("#myAlert").on("close.bs.alert", function() {
- console.log("警告框即将关闭");
- });
-
- $("#myAlert").on("closed.bs.alert", function() {
- console.log("警告框已关闭");
- });
-
- // 通过JavaScript关闭警告框
- $("#closeAlertBtn").click(function() {
- $("#myAlert").alert("close");
- });
- });
- // 4. 使用Bootstrap的下拉菜单
- $(document).ready(function() {
- // 监听下拉菜单事件
- $(".dropdown").on("show.bs.dropdown", function() {
- console.log("下拉菜单即将显示");
- });
-
- $(".dropdown").on("shown.bs.dropdown", function() {
- console.log("下拉菜单已显示");
- });
-
- $(".dropdown").on("hide.bs.dropdown", function() {
- console.log("下拉菜单即将隐藏");
- });
-
- $(".dropdown").on("hidden.bs.dropdown", function() {
- console.log("下拉菜单已隐藏");
- });
-
- // 通过JavaScript切换下拉菜单
- $("#toggleDropdownBtn").click(function() {
- $("#myDropdown").dropdown("toggle");
- });
- });
复制代码
7.2 jQuery与AngularJS集成
- // 1. 在AngularJS控制器中使用jQuery
- angular.module("myApp", []).controller("myController", function($scope) {
- // 使用jQuery选择元素
- $scope.init = function() {
- // 等待DOM渲染完成
- setTimeout(function() {
- // 使用jQuery操作DOM
- $("#myElement").addClass("highlight");
-
- // 使用jQuery绑定事件
- $("#myButton").click(function() {
- $scope.$apply(function() {
- $scope.message = "按钮被点击";
- });
- });
- }, 0);
- };
-
- $scope.init();
- });
- // 2. 在AngularJS指令中使用jQuery
- angular.module("myApp").directive("myDirective", function() {
- return {
- restrict: "A",
- link: function(scope, element, attrs) {
- // element是一个jQuery对象(如果jQuery在Angular之前加载)
- element.css("color", "red");
-
- // 使用jQuery事件
- element.on("click", function() {
- scope.$apply(function() {
- scope.message = "指令元素被点击";
- });
- });
- }
- };
- });
- // 3. 解决jQuery和AngularJS的冲突
- // 确保在加载Angular之前加载jQuery
- // 然后Angular会自动使用jQuery而不是jQLite
- // 4. 在AngularJS服务中使用jQuery
- angular.module("myApp").service("myService", function($q) {
- this.loadData = function() {
- var deferred = $q.defer();
-
- // 使用jQuery的AJAX
- $.ajax({
- url: "/api/data",
- success: function(data) {
- deferred.resolve(data);
- },
- error: function() {
- deferred.reject("加载数据失败");
- }
- });
-
- return deferred.promise;
- };
- });
- // 在控制器中使用服务
- angular.module("myApp").controller("anotherController", function($scope, myService) {
- myService.loadData().then(function(data) {
- $scope.data = data;
- }, function(error) {
- $scope.error = error;
- });
- });
复制代码
7.3 jQuery与React集成
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,并在实际项目中发挥其最大的价值。
版权声明
1、转载或引用本网站内容(jQuery 1.11 完整手册 开发者必备资源 全面覆盖API参考 实例教程 常见问题解答 从入门到精通 助力高效开发 解决实际项目问题)须注明原网址及作者(威震华夏关云长),并标明本网站网址(https://pixtech.cc/)。
2、对于不当转载或引用本网站内容而引起的民事纷争、行政处理或其他损失,本网站不承担责任。
3、对不遵守本声明或其他违法、恶意使用本网站内容者,本网站保留追究其法律责任的权利。
本文地址: https://pixtech.cc/thread-41600-1-1.html
|
|