"""Offline Playwright Chromium lab for jQuery Chapter 1 (tutorial)."""
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) {
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.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.addClass = function (cls) {
return this.each(function (_, el) { el.classList.add(cls); });
};
JQ.prototype.text = function (val) {
if (val === undefined) {
return this.elements[0] ? this.elements[0].textContent : "";
}
return this.each(function (_, el) { el.textContent = val; });
};
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_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery 教程离线实验</title>
<script>{MINI_JQ}</script>
<script>
window.__events = [];
$(document).ready(function () {{
window.__events.push("dom_ready");
$("p.click-hide").click(function () {{
window.__events.push("click:" + this.id);
$(this).hide();
}});
$("#btn-batch").click(function () {{
$(".item").hide();
}});
$("#btn-chain").click(function () {{
$("#box")
.css("color", "rgb(15, 118, 110)")
.addClass("active")
.text("已链式更新");
}});
}});
</script>
</head>
<body>
<p id="p1" class="click-hide">第一段:点击隐藏</p>
<p id="p2" class="click-hide">第二段:点击隐藏</p>
<p id="p3" class="click-hide">第三段:保持可见</p>
<div class="item" id="i1">条目 1</div>
<div class="item" id="i2">条目 2</div>
<div class="item" id="i3">条目 3</div>
<button id="btn-batch" type="button">批量隐藏条目</button>
<div id="box">初始内容</div>
<button id="btn-chain" type="button">执行链式调用</button>
</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: $(document).ready + $("p").click($(this).hide())
initial_displays = page.evaluate(
"() => ['p1','p2','p3'].map(id => getComputedStyle(document.getElementById(id)).display)"
)
page.locator("#p1").click()
after_p1 = page.evaluate(
"() => ['p1','p2','p3'].map(id => getComputedStyle(document.getElementById(id)).display)"
)
page.locator("#p2").click()
after_p2 = page.evaluate(
"() => ['p1','p2','p3'].map(id => getComputedStyle(document.getElementById(id)).display)"
)
events_log = page.evaluate("() => window.__events.slice()")
exp1 = {
"initial_displays": ["block", "block", "block"],
"after_click_p1": ["none", "block", "block"],
"after_click_p2": ["none", "none", "block"],
"events": ["dom_ready", "click:p1", "click:p2"],
}
act1 = {
"initial_displays": initial_displays,
"after_click_p1": after_p1,
"after_click_p2": after_p2,
"events": events_log,
}
cases.append(dict(name="dom_ready_click_hide", passed=(act1 == exp1), expected=exp1, actual=act1))
# Case 2: batch hide via class selector
matched_before = page.evaluate("() => $('.item').length")
page.locator("#btn-batch").click()
item_displays = page.evaluate(
"() => ['i1','i2','i3'].map(id => getComputedStyle(document.getElementById(id)).display)"
)
exp2 = {"matched_count": 3, "displays_after_batch_hide": ["none", "none", "none"]}
act2 = {"matched_count": matched_before, "displays_after_batch_hide": item_displays}
cases.append(dict(name="batch_selector_hide", passed=(act2 == exp2), expected=exp2, actual=act2))
# Case 3: chaining css + addClass + text
page.locator("#btn-chain").click()
act3 = page.evaluate(
"""() => {
const box = document.getElementById('box');
return {
color: getComputedStyle(box).color,
has_active: box.classList.contains('active'),
text: box.textContent,
alias_equal: window.$ === window.jQuery
};
}"""
)
exp3 = {
"color": "rgb(15, 118, 110)",
"has_active": True,
"text": "已链式更新",
"alias_equal": True,
}
cases.append(dict(name="chaining_and_alias_surface", passed=(act3 == exp3), expected=exp3, actual=act3))
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-tutorial-lab/explore-tutorial.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a915.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip