Skip to content

jquery_examples

通过简洁的示例 exploring common jQuery tasks explore common jQuery tasks 通过简洁的示例 concise examples探索常见的 jQuery 任务。记住将你的代码包裹 wrapping 在 $(function() { ... }); 中,以确保 DOM 准备就绪 ready。

$("p").hide(); 演示 demonstrates 如何隐藏 hiding 所有 <p> 元素 elements。

$("#main-image").hide(); 演示如何隐藏 hiding id="main-image" 的元素 element。

$(". MuiDialog-paper").hide(); 演示如何隐藏 hiding 所有具有 class=" MuiDialog-paper" 的元素 elements。

$(this).hide(); 在事件处理程序 event handler 内部,隐藏 hides 触发 triggered 事件 event 的特定元素 specific element(例如,被点击 clicked 的按钮 button)。

选择器示例解释

$("button").on('click', function() { alert('Button clicked!'); }); 当任何 <button> 被点击 clicked 时显示一个提示框 alert。.on() 是事件绑定 event binding 的标准方法 standard method。

$("img").on('dblclick', function() { $(this).fadeOut(); }); 当图片 image 被双击 double-clicked 时,以淡出效果 fade effect 隐藏 hides 它。

$("#menu").on('mouseenter', function() { $(this).addClass('hover'); }); 当鼠标指针 mouse pointer 进入 enters id="menu" 的元素 element 时,添加 adds hover 类 class。

$("#menu").on('mouseleave', function() { $(this).removeClass('hover'); }); 当鼠标指针 mouse pointer 离开 leaves id="menu" 的元素 element 时,移除 removes hover 类 class。

$(". MuiDialog-paper").hover(function() { $(this).toggleClass('highlight'); }); 鼠标进入 mouse enter 时为 class=" MuiDialog-paper" 的元素 elements 添加 adds highlight 类 class,离开 mouse leave 时移除 removes 它。hover() 是 mouseenter 和 mouseleave 的快捷方式 shortcut。

$("input[type='text']").on('focus', function() { $(this).css('border-color', 'blue'); }); 当文本输入字段 text input field 获得焦点 gains focus 时改变 changes 边框颜色 border color。

$("input[type='text']").on('blur', function() { $(this).css('border-color', ''); }); 当文本输入字段 text input field 失去焦点 loses focus 时重置 resets 边框颜色 border color。

事件处理示例解释

$("#details").hide(); 立即 Immediately 隐藏 hides id="details" 的元素 element。

$("#details").show(); 立即 Immediately 显示 shows id="details" 的元素 element。

$("#details").toggle(); 切换 Toggles id="details" 的元素的可见性 visibility(隐藏时显示 shows if hidden,显示时隐藏 hides if shown)。

$("span.optional").hide(500); 在 over 500 毫秒 milliseconds 内隐藏 hides 具有 class="optional" 的元素 elements。

显示/隐藏示例解释

$("#notification").fadeIn('slow'); 使 Graduallly 逐渐 fades in 淡入 id="notification" 的元素 element(‘slow’ 速度 duration)。

$("#notification").fadeOut(1000); 使 Graduallly 逐渐 fades out 淡出 id="notification" 的元素 element,持续 over 1000 毫秒 milliseconds(1 秒 second)。

$("#notification").fadeToggle('fast'); 在 Toggles between 淡入 fading in 和淡出 fading out 之间切换(‘fast’ 速度 duration)。

$("#overlay").fadeTo(500, 0.5); 使 Fades id="overlay" 的元素 element 在 over 500 毫秒 milliseconds 内淡入到 to 50% 的不透明度 opacity。

淡入淡出示例解释

$("#details-panel").slideDown(); 使 Slides down id="details-panel" 的元素 element 向下滑动(显示 reveals)。

$("#details-panel").slideUp('fast'); 使 Slides up id="details-panel" 的元素 element 向上滑动(快速 quickly 隐藏 hides)。

$("#details-panel").slideToggle(500); 在 Toggles between 向下滑动 sliding down 和向上滑动 sliding up 之间切换,持续 over 500 毫秒 milliseconds。

滑动示例解释

$("#box").animate({ left: '250px' }); 将 Animates id="box" 的元素的 left CSS 属性 property 动画化到 250px。

$("#box").animate({ opacity: 0.5, height: '50px', width: '50px' }, 1000); 在 over 1 秒 second 内动画化 Animates 多个 multiple CSS 属性 properties (opacity, height, width)。

$("#box").animate({ left: '+=50px' }, 'fast'); 将 Animates left 属性 property 在 its current value 其当前值的基础上 增加 increasing 50px 进行动画。

$("#box").animate({ height: 'toggle' }); 动画化 Animates 高度 height 以显示 show 或隐藏 hide 元素 element。

$("#box").animate({ width: '200px' }).animate({ height: '200px' }); 动画队列 Queues animations:首先动画化 animates 宽度 width,然后 then 动画化 animates 高度 height。

动画 Animation 示例解释 explained(注意 Note:对于复杂的 complex 动画 animations,CSS 过渡 transitions/动画 animations 通常性能 performance 更优 more performant)。

$("#sliding-panel").stop(); 停止 Stops 在 id="sliding-panel" 的元素 element 上当前运行 running 的动画 animation。

$("#animated-box").stop(true, true); 清除 Clears 动画队列 animation queue 并立即 immediately 跳到 jumps to 当前动画 current animation 的最终状态 final state。

停止动画示例解释

const text = $("p#intro").text(); 获取 Gets id="intro" 的元素的组合文本内容 combined text content(剥离 strips HTML 标签 tags)。

const content = $("div#content").html(); 获取 Gets id="content" 的元素的 HTML 内容 HTML content(包含 including 标签 tags)。

const name = $("input#username").val(); 获取 Gets id="username" 的输入字段 input field 的当前值 current value。

const linkUrl = $("a#w3s-link").attr('href'); 获取 Gets id="w3s-link" 的链接 link 的 href 属性 attribute 值。

获取内容/属性示例解释

$("p#intro").text('New introduction text.'); 设置 Sets id="intro" 的元素的文本内容 text content。

$("div#content").html('<h2>New Title</h2><p>New paragraph.</p>'); 设置 Sets id="content" 的元素的 HTML 内容 HTML content。

$("input#username").val('DefaultUser'); 设置 Sets id="username" 的输入字段 input field 的值 value。

$("a#w3s-link").attr('href', 'https://www.w3schools.com/jquery/'); 设置 Sets id="w3s-link" 的链接 link 的 href 属性 attribute。

$("img").attr({ src: 'new_image.jpg', alt: 'New Alt Text' }); 为所有 <img> 元素 elements 设置 Sets 多个 multiple 属性 attributes (src 和 alt)。

$("p").html(function(index, oldHtml) { return oldHtml + ' **(Updated)**'; }); 使用 Uses 回调函数 callback function 修改 modify 每个段落 paragraph 的 HTML 内容 HTML content,并在末尾添加 appending ’ (Updated)’。

设置内容/属性示例解释

$("ul#list").append('<li>New Item</li>'); 在 id="list" 的 <ul> 末尾 end 添加 Appends 一个新的列表项 new list item。

$("ul#list").prepend('<li>First Item</li>'); 在 id="list" 的 <ul> 开头 beginning 添加 Prepends 一个新的列表项 new list item。

$("p#first-para").after('<hr>'); 在 id="first-para" 的段落 paragraph 之后 immediately after 立即插入 Inserts 一条水平线 horizontal rule <hr>。

$("h2#title").before('<p>Introduction:</p>'); 在 id="title" 的标题 heading 之前 immediately before 立即插入 Inserts 一个段落 paragraph。

添加元素示例解释

$(". MuiDialog-paper").remove(); 从 DOM 中移除 Removes 所有具有 class=" MuiDialog-paper" 的元素 elements。

$("#container").empty(); 移除 Removes id="container" 的元素 element 内部 inside 的所有子元素 child elements,但 leaves 保留容器 container 本身。

$("p").remove('.old'); 仅移除 Removes only 同时同时具有 have also old 类的 <p> 元素 elements。

移除元素示例解释

$("#header").addClass('fixed-header'); 为 Adds id="header" 的元素 element 添加 fixed-header 类 class。

$("button").addClass('btn btn-primary'); 为所有 <button> 元素 elements 添加 Adds 多个 multiple 类 classes(btn 和 btn-primary)。

$("#header").removeClass('fixed-header'); 从 Removes id="header" 的元素 element 中移除 fixed-header 类 class。

$("#menu-item").toggleClass('active'); 如果 it’s not present id="menu-item" 的元素 element 没有则 Adds 添加 active 类 class,如果 is present 存在则 removes 移除它。

CSS 类操作 manipulation 示例解释

const bgColor = $("#main").css('background-color'); 获取 Gets id="main" 的元素的 background-color CSS 属性 property 的计算值 computed value。

$("h1").css('color', 'blue'); 将 Sets 所有 <h1> 元素 elements 的 color CSS 属性 property 设置为 to blue。

$(". MuiDialog-paper").css({ 'background-color': 'yellow', 'font-weight': 'bold' }); 为所有具有 class=" MuiDialog-paper" 的元素 elements 设置 Sets 多个 multiple CSS 属性 properties。

CSS 属性示例解释

const w = $("#image").width(); const h = $("#image").height(); 获取 Gets 元素的计算 computed 宽度 width 和高度 height(不包含 excluding padding, border, margin)。

const innerW = $("#container").innerWidth(); 获取 Gets 包含 including padding 但不包含 but not border 的宽度 width。

const outerW = $("#container").outerWidth(); 获取 Gets 包含 including padding 和 and border 的宽度 width。

const outerWMargin = $("#container").outerWidth(true); 获取 Gets 包含 including padding, border, 和 and margin 的宽度 width。

const docHeight = $(document).height(); const winHeight = $(window).height(); 分别 respectively 获取 Gets 整个 entire HTML 文档 document 和浏览器视口 browser viewport 的高度 height。

$("#resizable").width(300).height(200); 设置 Sets 元素的宽度 width 和高度 height。

尺寸 Dimension 示例解释

$("span#item").parent(); 选择 Selects id="item" 的 <span> 元素的直接 parent 父元素。

$("span#item").parents(); 选择 Selects 所有祖先 ancestor 元素 elements (parent, grandparent, etc.),直到 up to <html>。

$("span#item").parents('ul'); 选择 Selects 所有 specifically 是 <ul> 元素的 ancestor 祖先元素 elements。

$("li.active").parentsUntil('div.container'); 选择 Selects 活动 active <li> 和 div.container 之间的所有 all 祖先 ancestors,但不包括 not including 容器 container 本身 itself。

祖先遍历 traversal 示例解释

$("div#main-content").children(); 选择 Selects 该 <div> 的所有 direct child 直接子元素 elements。

$("div#main-content").children('p. MuiDialog-paper'); 仅选择 Selects only 是具有 MuiDialog-paper 类的 <p> 元素的 direct children 直接子元素。

$("div#main-content").find('span'); 选择 Selects 作为该 <div> 的 descendants 后代(children, grandchildren, etc.)的所有 <span> 元素 elements。

后代遍历 traversal 示例解释

$("h2.current").siblings(); 选择 Selects 具有 current 类的 <h2> 的所有 sibling 同级元素 elements。

$("h2.current").siblings('p'); 仅选择 Selects only 是 <p> 标签 tags 的 sibling 同级元素 elements。

$("li.active").next(); 选择 Selects 紧随其后 immediately following 的 sibling 同级元素 element。

$("li.active").nextAll('li'); 选择 Selects 所有 following 紧随其后且是 <li> 标签 tags 的 sibling 同级元素 elements。

$("li#start").nextUntil('li#end'); 选择 Selects 具有 id="start" 的元素和 and 具有 id="end" 的元素 element 之间的所有 sibling 同级元素 elements。

$("li.active").prev(); 选择 Selects 紧邻 immediately preceding 的前一个 sibling 同级。

$("li.active").prevAll(); 选择 Selects 所有 preceding 前面的 siblings 同级。

$("li#start").prevUntil('li#stop'); 选择 Selects #start 和 and #stop 之间的 preceding 前面 siblings 同级。

同级遍历 traversal 示例解释

$("li").first(); 在 among 所有 matched 匹配的 <li> 元素 elements 中,选择 Selects 第一个 first <li> 元素 element。

$("li").last(); 在 among 所有 matched 匹配的 <li> 元素 elements 中,选择 Selects 最后一个 last <li> 元素 element。

$("li").eq(2); 选择 Selects 第三个 third <li> 元素 element(索引 index 从 starts at 0 开始)。

$("p").filter('. MuiDialog-paper'); 过滤 Filters the selection 选择的 paragraphs 段落 to include only 仅包含 those with 那些具有 class=" MuiDialog-paper" 的段落。

$("p").not('. MuiDialog-paper'); 过滤 Filters the selection 选择的 paragraphs 段落 to exclude 排除 those with 那些具有 class=" MuiDialog-paper" 的段落。

过滤 Filtering 示例解释

$("#result").load('content/data.html'); 将 Loads data.html 的内容 content 加载到 into id="result" 的元素 element 中。

$("#result").load('content/data.html #specific-section'); 仅 Loads only 将 data.html 中 id="specific-section" 的元素 element 内容 content 加载到 into #result 中。

$("#result").load('content/data.php', { name: 'John', location: 'Boston' }, function(response, status, xhr) { if (status == 'error') { console.error('Error loading data:', xhr.statusText); } }); 从 Loads content from data.php 加载内容,发送 sending 数据 data,并包含 includes 一个回调函数 callback function 来处理 handle 完成 completion(success 成功或 error 错误)。注意 Note:现代实践 Modern practice 通常 prefers 更倾向于使用 with Promises 支持 Promise 的 $.get 或 $.post。

AJAX load 示例解释

$.get('api/users.json', function(data) { console.log('Data received:', data); }).fail(function() { console.error('Failed to get data.'); }); 使用 Uses $.get() 从 api/users.json 获取 retrieve 数据 data。它使用 uses .done()(在 callback shorthand 回调简写中 implicit 隐式包含)和 and .fail() 来 handling 处理 asynchronous response 异步响应(Promise-like behavior 类似 Promise 的行为)。

$.post('api/submit-form.php', { name: 'Jane', email: 'jane@example.com' }) .done(function(response) { console.log('Server response:', response); }) .fail(function() { console.error('Failed to post data.'); }); 使用 Uses $.post() 将数据 data 发送 to 到 api/submit-form.php,并使用 and handles .done() 和 and .fail() 处理 response 响应。

AJAX GET/POST 示例解释 explained(注意 Note:原生的 native fetch API 是 JavaScript 中 AJAX 的 modern standard 现代标准,但在 jQuery 项目 projects 中 $.get/$.post 仍然 common 很常见)。