蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-syntax.py
explore-syntax.py170 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/jquery-syntax-lab/explore-syntax.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-syntax.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a909.zip

下载课程关联工程包:jQuery

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习