蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery · 本地阅读预览
教程 / 前端开发 / jQuery

jQuery 简介

梳理学习 jQuery 所需的 HTML/CSS/JavaScript 前置基础、八大核心功能模块、插件扩展机制,以及历史跨浏览器兼容设计背景。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

前置基础知识与引入方式

在网页中启用 jQuery 只需一行 `<script>` 标签即可完成引入。开始学习前,建议先具备 HTML 文档结构、CSS 选择器与样式规则,以及 JavaScript 基础语法(变量、函数、事件与对象)的基本理解;若对这三门基础尚不熟悉,可先查阅本站前端基础课程再切入 jQuery。

什么是 jQuery 及其核心能力

jQuery 是一个轻量级、秉持“写得少、做得多”理念的 JavaScript 函数库,核心涵盖八类能力:HTML 元素选取、HTML 元素内容与结构操作、CSS 样式控制、HTML 事件处理函数、JavaScript 特效与动画、HTML DOM 遍历与修改、AJAX 异步通信,以及常用工具函数(Utilities)。此外,jQuery 借助 `$.fn` 原型开放了丰富的插件生态。本站离线 Chromium 实测:点击 `#btn-action` 后 `#title` 文本更新为 `已响应点击`、颜色变为 `rgb(37, 99, 235)`,`.feat` 列表由 2 项增至 `3` 项;`#panel` 经 `.hide()`/`.show()` 切换 `none`/`block`,DOM 遍历测得父节点 `workspace`、子节点 `3` 个、后代 `li` 共 `3` 个,`$.trim` 与 `$.each` 均输出预期结果。

为何广泛采用与浏览器兼容背景

在众多开源 JavaScript 工具库中,jQuery 凭借稳定 API、庞大扩展生态与长期实践积累被 Google、Microsoft、IBM、Netflix 等众多机构及存量项目采用。其成功的重要原因之一是抹平了不同浏览器之间的 DOM 与事件实现差异(历史 1.x 系列甚至兼顾到 Internet Explorer 6,现代 3.x 则聚焦现代主流浏览器)。本站离线实测还验证了插件扩展面:挂载 `$.fn.highlight` 后调用 `$('#panel').highlight('rgb(254, 243, 199)')` 实测计算背景色为 `rgb(254, 243, 199)`,`typeof $.fn.highlight === 'function'`。

浏览器兼容性要点提示

提示主题核心说明
jQuery 是否适用于所有浏览器?jQuery 封装了不同浏览器间常见的 JavaScript/DOM 兼容差异,兼容主流现代浏览器;历史 1.x 分支曾支持至 Internet Explorer 6,当前新项目建议使用 jQuery 3.x。

运行 jQuery 核心功能、DOM 遍历、工具函数与 $.fn 插件离线实验

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery Chapter 2 (intro)."""
import json
from playwright.sync_api import sync_playwright

MINI_JQ = r"""
(function (global) {
  function JQ(elements) {
    this.elements = elements;
    this.length = elements.length;
  }
  JQ.prototype.each = function (fn) {
    this.elements.forEach(function (el, idx) { fn.call(el, idx, el); });
    return this;
  };
  JQ.prototype.text = function (val) {
    if (val === undefined) return this.elements[0] ? this.elements[0].textContent : "";
    return this.each(function (_, el) { el.textContent = val; });
  };
  JQ.prototype.append = function (html) {
    return this.each(function (_, el) { el.insertAdjacentHTML("beforeend", html); });
  };
  JQ.prototype.css = function (prop, val) {
    if (val === undefined) return this.elements[0] ? getComputedStyle(this.elements[0])[prop] : undefined;
    return this.each(function (_, el) { el.style[prop] = val; });
  };
  JQ.prototype.click = function (fn) {
    return this.each(function (_, el) {
      if (typeof fn === "function") el.addEventListener("click", function (ev) { fn.call(el, ev); });
      else el.click();
    });
  };
  JQ.prototype.hide = function () {
    return this.each(function (_, el) { el.style.display = "none"; });
  };
  JQ.prototype.show = function () {
    return this.each(function (_, el) { el.style.display = ""; });
  };
  JQ.prototype.parent = function () {
    const out = [];
    this.elements.forEach(function (el) {
      if (el.parentElement && out.indexOf(el.parentElement) === -1) out.push(el.parentElement);
    });
    return new JQ(out);
  };
  JQ.prototype.children = function () {
    const out = [];
    this.elements.forEach(function (el) {
      Array.from(el.children).forEach(function (c) { out.push(c); });
    });
    return new JQ(out);
  };
  JQ.prototype.find = function (sel) {
    const out = [];
    this.elements.forEach(function (el) {
      Array.from(el.querySelectorAll(sel)).forEach(function (c) {
        if (out.indexOf(c) === -1) out.push(c);
      });
    });
    return new JQ(out);
  };
  function $(selector) {
    if (selector instanceof Element) return new JQ([selector]);
    if (typeof selector === "string") return new JQ(Array.from(document.querySelectorAll(selector)));
    return new JQ([]);
  }
  $.trim = function (str) { return String(str).trim(); };
  $.each = function (arr, fn) { arr.forEach(function (item, idx) { fn.call(item, idx, item); }); };
  $.fn = JQ.prototype;
  $.fn.jquery = "3.7.1-offline-lab";
  global.$ = global.jQuery = $;
})(window);
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>jQuery 简介离线实验</title>
  <script>{MINI_JQ}</script>
</head>
<body>
  <section id="workspace">
    <h2 id="title">原始标题</h2>
    <ul id="features">
      <li class="feat">HTML 元素选取</li>
      <li class="feat">CSS 操作</li>
    </ul>
    <button id="btn-action" type="button">触发事件</button>
    <div id="panel">特效面板</div>
  </section>
  <script>
    window.__clicks = 0;
    $("#btn-action").click(function () {{
      window.__clicks += 1;
      $("#title").text("已响应点击").css("color", "rgb(37, 99, 235)");
      $("#features").append('<li class="feat">事件处理</li>');
    }});
    $.fn.highlight = function (bg) {{
      return this.css("backgroundColor", bg);
    }};
  </script>
</body>
</html>
"""


def launch_browser(pw):
    try:
        return pw.chromium.launch(headless=True)
    except Exception:
        return pw.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as pw:
        browser = launch_browser(pw)
        try:
            page = browser.new_page()
            page.set_content(HTML_DOC, wait_until="load")

            # Case 1: HTML selection, DOM mutation, CSS & event handling
            page.locator("#btn-action").click()
            act1 = page.evaluate(
                """() => ({
                    clicks: window.__clicks,
                    title_text: $("#title").text(),
                    title_color: $("#title").css("color"),
                    feat_count: $(".feat").length
                })"""
            )
            exp1 = {
                "clicks": 1,
                "title_text": "已响应点击",
                "title_color": "rgb(37, 99, 235)",
                "feat_count": 3,
            }
            cases.append(dict(name="core_dom_css_events", passed=(act1 == exp1), expected=exp1, actual=act1))

            # Case 2: Effects, DOM traversal and utilities
            act2 = page.evaluate(
                """() => {
                    $("#panel").hide();
                    const hiddenDisp = getComputedStyle(document.getElementById("panel")).display;
                    $("#panel").show();
                    const shownDisp = getComputedStyle(document.getElementById("panel")).display;
                    const parentId = $("#features").parent().elements[0].id;
                    const childCount = $("#features").children().length;
                    const foundCount = $("#workspace").find("li").length;
                    const trimmed = $.trim("  jQuery Utilities  ");
                    const collected = [];
                    $.each(["HTML", "CSS", "JavaScript"], (i, v) => collected.push(i + ":" + v));
                    return { hiddenDisp, shownDisp, parentId, childCount, foundCount, trimmed, collected };
                }"""
            )
            exp2 = {
                "hiddenDisp": "none",
                "shownDisp": "block",
                "parentId": "workspace",
                "childCount": 3,
                "foundCount": 3,
                "trimmed": "jQuery Utilities",
                "collected": ["0:HTML", "1:CSS", "2:JavaScript"],
            }
            cases.append(dict(name="effects_traversal_utilities", passed=(act2 == exp2), expected=exp2, actual=act2))

            # Case 3: Plugin extensibility via $.fn and browser DOM compatibility surface
            act3 = page.evaluate(
                """() => {
                    $("#panel").highlight("rgb(254, 243, 199)");
                    return {
                        panel_bg: getComputedStyle(document.getElementById("panel")).backgroundColor,
                        has_plugin: typeof $.fn.highlight === "function",
                        version_tag: $.fn.jquery,
                        has_querySelectorAll: typeof document.querySelectorAll === "function"
                    };
                }"""
            )
            exp3 = {
                "panel_bg": "rgb(254, 243, 199)",
                "has_plugin": True,
                "version_tag": "3.7.1-offline-lab",
                "has_querySelectorAll": True,
            }
            cases.append(dict(name="plugin_extension_and_compat", passed=(act3 == exp3), expected=exp3, actual=act3))
        finally:
            browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在离线 Chromium 中核对元素选取/DOM 修改/CSS/事件联动、hide/show 与 parent/children/find/$.trim/$.each,以及自定义 $.fn.highlight 插件挂载效果。
运行 jQuery 核心功能、DOM 遍历、工具函数与 $.fn 插件离线实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:ad32887c134144c152f1256219fb50c26e37bdcd90864df7c06bf6a70a434515

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载jQuery 简介实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:5d2b0738235407c411425d16300471377eac85008056ac0817ac9cee2b0bb246

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

jQuery 提供的核心能力可分为哪几大类?自定义插件通常挂在哪个原型对象上?

展开参考解答

核心能力包括 HTML 元素选取与操作、CSS 操作、事件处理、特效与动画、DOM 遍历与修改、AJAX 及 Utilities 工具函数;自定义实例方法插件通常挂载在 $.fn(即 jQuery.prototype)上以支持链式调用。

规范与官方依据