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

jQuery 语法

核对 $(selector).action() 基础语法构成、四种常见隐藏写法、文档就绪事件 $(document).ready() 及其简洁写法 $(fn) 的执行时机差异。

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

学完这一章,你能够

基础语法 $(selector).action()

jQuery 的核心操作遵循 `$(selector).action()` 模式:美元符号 `$` 用于定义并调用 jQuery 工厂函数;括号内的 `selector`(选择器)基于 CSS 选择器语法查询并匹配一个或多个 HTML 元素;末尾的 `action()` 则对匹配结果集合执行具体操作。

四种最常见的入门表达式分别是:`$(this).hide()` 隐藏当前触发事件的元素;`$('p').hide()` 隐藏全部 `<p>` 元素;`$('p.test').hide()` 仅隐藏同时带有 `class="test"` 的 `<p>` 元素;`$('#test').hide()` 隐藏 `id="test"` 的唯一元素。本站离线 Chromium 实测:点击 `#self-p` 后该段落 `display` 变为 `none`;调用 `$('p.test').hide()` 仅隐藏 `#p-test`(`none`),同类的 `<span class="test">` 保持 `inline`、普通段落 `#p-plain` 保持 `block`;随后 `$('#test').hide()` 与 `$('p').hide()` 均精确匹配并隐藏对应节点;基础选择器查询测得 `$('p')` 共 `3` 项、`$('.test')` 共 `2` 项、`$("p.test")` 仅 `1` 项、`$('#s1 p')` 共 `3` 项。

文档就绪事件与简洁写法

将脚本包裹在 `$(document).ready(function(){ ... })` 中,可以防止代码在 DOM 树构建完成前提前运行。若在 `<head>` 中过早操作尚未解析的文档,可能出现试图隐藏不存在的元素或读取未加载完成图像尺寸失败等问题。本站离线实测直接在 `<head>` 顶部查询 `$('#late-target').length` 仅得到 `0`,而在 `$(document).ready()` 回调内查询到 `1` 个元素并成功将其 `display` 设为 `none`。

jQuery 还提供了等价的简洁写法 `$(function(){ ... })`,效果与 `$(document).ready(function(){ ... })` 完全一致,开发者可根据团队风格任选其一。本站离线实测同时注册完整写法与简洁写法,两者在 DOM 就绪后按注册先后依次执行,日志顺序精确为 `['document_ready', 'shorthand_ready']`。

选择器语法背景提示

提示主题核心说明
jQuery 选择器与 CSS 语法的关系jQuery 选择器以 CSS 选择器语法为基础并辅以部分自定义伪类扩展(早期文档曾提及吸收部分 XPath 思路,现代版本全面遵循 CSS 选择器与 Sizzle/原生选择器规范),熟悉 CSS 选择器即可快速上手。

运行四种基础语法表达式、过早执行对比与两种文档就绪写法实验

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery Chapter 4 (syntax)."""
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.ready = function (fn) {
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", fn);
    } else {
      fn();
    }
    return this;
  };
  JQ.prototype.click = function (fn) {
    return this.each(function (_, el) {
      el.addEventListener("click", function (ev) { fn.call(el, ev); });
    });
  };
  JQ.prototype.hide = function () {
    return this.each(function (_, el) { el.style.display = "none"; });
  };
  function $(selector) {
    if (typeof selector === "function") return new JQ([document]).ready(selector);
    if (selector === document || selector instanceof Element) return new JQ([selector]);
    if (typeof selector === "string") return new JQ(Array.from(document.querySelectorAll(selector)));
    return new JQ([]);
  }
  $.fn = JQ.prototype;
  $.fn.jquery = "3.7.1-offline-lab";
  global.$ = global.jQuery = $;
})(window);
"""

HTML_SYNTAX = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>jQuery 语法离线实验</title>
  <script>{MINI_JQ}</script>
  <script>
    // Runs in <head> BEFORE body exists
    window.__earlyCount = $("#late-target").length;
    window.__readyOrder = [];
    $(document).ready(function () {{
      window.__readyOrder.push("document_ready");
      window.__readyCount = $("#late-target").length;
      $("#late-target").hide();
    }});
    $(function () {{
      window.__readyOrder.push("shorthand_ready");
      $("#self-p").click(function () {{
        $(this).hide();
      }});
    }});
  </script>
</head>
<body>
  <div id="late-target">等待 DOM 就绪后隐藏</div>

  <section id="s1">
    <p id="self-p">点击隐藏当前元素</p>
    <p id="p-test" class="test">带 class="test" 的段落</p>
    <p id="p-plain">普通段落</p>
    <div id="test">id="test" 的块元素</div>
    <span class="test" id="span-test">非 p 的 .test</span>
  </section>
</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_SYNTAX, wait_until="load")

            # Case 1: Early <head> execution vs $(document).ready()
            act1 = page.evaluate(
                """() => ({
                    early_count: window.__earlyCount,
                    ready_count: window.__readyCount,
                    late_display: getComputedStyle(document.getElementById("late-target")).display
                })"""
            )
            exp1 = {"early_count": 0, "ready_count": 1, "late_display": "none"}
            cases.append(dict(name="document_ready_vs_early_head", passed=(act1 == exp1), expected=exp1, actual=act1))

            # Case 2: Shorthand $(fn) equivalence and execution order
            act2 = page.evaluate("() => ({ ready_order: window.__readyOrder })")
            exp2 = {"ready_order": ["document_ready", "shorthand_ready"]}
            cases.append(dict(name="shorthand_ready_order", passed=(act2 == exp2), expected=exp2, actual=act2))

            # Case 3: Four basic $(selector).action() forms
            page.locator("#self-p").click()
            after_this = page.evaluate("() => getComputedStyle(document.getElementById('self-p')).display")
            after_p_test = page.evaluate(
                """() => {
                    $("p.test").hide();
                    return {
                        p_test: getComputedStyle(document.getElementById("p-test")).display,
                        span_test: getComputedStyle(document.getElementById("span-test")).display,
                        p_plain: getComputedStyle(document.getElementById("p-plain")).display
                    };
                }"""
            )
            after_id_test = page.evaluate(
                """() => {
                    $("#test").hide();
                    return getComputedStyle(document.getElementById("test")).display;
                }"""
            )
            after_all_p = page.evaluate(
                """() => {
                    $("p").hide();
                    return ["self-p", "p-test", "p-plain"].map(id => getComputedStyle(document.getElementById(id)).display);
                }"""
            )
            act3 = {
                "this_hide": after_this,
                "p_dot_test_hide": after_p_test,
                "id_test_hide": after_id_test,
                "all_p_hide": after_all_p,
            }
            exp3 = {
                "this_hide": "none",
                "p_dot_test_hide": {"p_test": "none", "span_test": "inline", "p_plain": "block"},
                "id_test_hide": "none",
                "all_p_hide": ["none", "none", "none"],
            }
            cases.append(dict(name="four_basic_syntax_forms", passed=(act3 == exp3), expected=exp3, actual=act3))

            # Case 4: CSS selector foundation counts
            act4 = page.evaluate(
                """() => ({
                    all_p: $("p").length,
                    class_test: $(".test").length,
                    p_class_test: $("p.test").length,
                    descendant_s1_p: $("#s1 p").length
                })"""
            )
            exp4 = {"all_p": 3, "class_test": 2, "p_class_test": 1, "descendant_s1_p": 3}
            cases.append(dict(name="css_selector_foundation", passed=(act4 == exp4), expected=exp4, actual=act4))
        finally:
            browser.close()

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 <head> 过早查询返回 0 而 ready 回调返回 1 并隐藏节点、两种 ready 写法按序触发,以及 $(this)/p/p.test/#test 四种隐藏结果的精确计算样式。
运行四种基础语法表达式、过早执行对比与两种文档就绪写法实验

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

当前源码 SHA256:a564ee0df2fe883baef7b4fa8992c97bc0bc06c2841dc706b5186f4764d49cd6

下载本站示例源码

本地运行

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

下载jQuery 语法实验

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

ZIP SHA256:7f0199e2b334d64505e22805c5c4472fcb8b8feed424f1a7e0166c5ab21447f2

常见错误与边界

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

练习与解答

在 <head> 中直接执行 $('#late-target').hide() 与将其放入 $(function(){ ... }) 有何本质区别?

展开参考解答

浏览器自上而下解析 HTML,执行 <head> 中裸露脚本时 <body> 内的 #late-target 尚未创建,匹配结果为 0;放入 $(function(){ ... })(即 $(document).ready 的简写)后会推迟到 DOM 解析完成再执行,确保节点存在。

规范与官方依据