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

离线 Chromium 实测 text()/html()/val()/attr() 直接写入、多属性对象与回调写入

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-dom-set.py
explore-dom-set.py223 行
"""Offline Playwright Chromium lab for jQuery Chapter 15 (dom-set)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
</head>
<body>
  <p id="test1">这是一个段落。</p>
  <p id="test2">这是另外一个段落。</p>
  <input id="test3" type="text" value="初始值">
  <button id="btn1" type="button">设置文本</button>
  <button id="btn2" type="button">设置 HTML</button>
  <button id="btn3" type="button">设置值</button>

  <p id="cb-text">原文本段落</p>
  <p id="cb-html">原 <em>HTML</em> 段落</p>
  <p class="note">条目A</p>
  <p class="note">条目B</p>
  <button id="btn-cb1" type="button">回调设置文本</button>
  <button id="btn-cb2" type="button">回调设置 HTML</button>

  <a id="doc-link" href="https://api.jquery.com" title="旧标题">jQuery 文档</a>
  <button id="btn-attr1" type="button">设置单个属性</button>
  <button id="btn-attr2" type="button">设置多个属性</button>
  <button id="btn-attr3" type="button">回调设置属性</button>

  <script>
    (function () {
      function JQ(els) {
        this.els = Array.from(els);
        this.length = this.els.length;
      }

      JQ.prototype.click = function (fn) {
        this.els.forEach((el) => el.addEventListener('click', fn));
        return this;
      };

      JQ.prototype.text = function (val) {
        if (val === undefined) return this.els.map((e) => e.textContent).join('');
        this.els.forEach((el, i) => {
          const next = typeof val === 'function' ? val.call(el, i, el.textContent) : val;
          if (next !== undefined) el.textContent = String(next);
        });
        return this;
      };

      JQ.prototype.html = function (val) {
        if (val === undefined) return this.els[0] ? this.els[0].innerHTML : undefined;
        this.els.forEach((el, i) => {
          const next = typeof val === 'function' ? val.call(el, i, el.innerHTML) : val;
          if (next !== undefined) el.innerHTML = String(next);
        });
        return this;
      };

      JQ.prototype.val = function (val) {
        if (val === undefined) return this.els[0] ? this.els[0].value : undefined;
        this.els.forEach((el, i) => {
          const next = typeof val === 'function' ? val.call(el, i, el.value) : val;
          if (next !== undefined) el.value = String(next);
        });
        return this;
      };

      JQ.prototype.attr = function (nameOrMap, val) {
        if (typeof nameOrMap === 'object' && nameOrMap !== null) {
          this.els.forEach((el, i) => {
            for (const [k, v] of Object.entries(nameOrMap)) {
              const next = typeof v === 'function' ? v.call(el, i, el.getAttribute(k)) : v;
              if (next !== undefined) el.setAttribute(k, String(next));
            }
          });
          return this;
        }
        if (val === undefined) {
          if (!this.els[0]) return undefined;
          const v = this.els[0].getAttribute(nameOrMap);
          return v === null ? undefined : v;
        }
        this.els.forEach((el, i) => {
          const orig = el.getAttribute(nameOrMap);
          const next = typeof val === 'function' ? val.call(el, i, orig === null ? undefined : orig) : val;
          if (next !== undefined) el.setAttribute(nameOrMap, String(next));
        });
        return this;
      };

      window.$ = function (sel) {
        return new JQ(document.querySelectorAll(sel));
      };

      $('#btn1').click(function () { $('#test1').text('Hello world!'); });
      $('#btn2').click(function () { $('#test2').html('<b>Hello world!</b>'); });
      $('#btn3').click(function () { $('#test3').val('jQuery 教程'); });

      $('#btn-cb1').click(function () {
        $('#cb-text').text(function (i, origText) {
          return '旧文本: ' + origText + ' 新文本: Hello world! (index: ' + i + ')';
        });
      });

      $('#btn-cb2').click(function () {
        $('#cb-html').html(function (i, origHtml) {
          return '旧 html: ' + origHtml + ' 新 html: Hello <b>world!</b> (index: ' + i + ')';
        });
      });

      $('#btn-attr1').click(function () {
        $('#doc-link').attr('href', 'https://api.jquery.com/category/manipulation/');
      });

      $('#btn-attr2').click(function () {
        $('#doc-link').attr({
          href: 'https://api.jquery.com',
          title: 'jQuery 官方文档',
        });
      });

      $('#btn-attr3').click(function () {
        $('#doc-link').attr('href', function (i, origValue) {
          return origValue + '/attr/' + i;
        });
      });
    })();
  </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 p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1000, "height": 700})
        page.set_content(HTML_DOC, wait_until="load")

        # Case 1: basic text(), html(), val() setters & HTML escaping difference
        page.click("#btn1")
        page.click("#btn2")
        page.click("#btn3")
        c1 = page.evaluate("""() => {
            const t1 = $('#test1').text();
            const t2Html = $('#test2').html();
            const t2BoldCount = document.querySelectorAll('#test2 b').length;
            const t3Val = $('#test3').val();
            const probe = document.createElement('p');
            probe.id = 'esc-probe';
            document.body.appendChild(probe);
            $('#esc-probe').text('<b>不解析标签</b>');
            const escBoldCount = document.querySelectorAll('#esc-probe b').length;
            const escText = $('#esc-probe').text();
            return { t1, t2Html, t2BoldCount, t3Val, escBoldCount, escText };
        }""")
        exp1 = {
            "t1": "Hello world!",
            "t2Html": "<b>Hello world!</b>",
            "t2BoldCount": 1,
            "t3Val": "jQuery 教程",
            "escBoldCount": 0,
            "escText": "<b>不解析标签</b>",
        }
        cases.append(dict(name="set_text_html_val_basic", expected=exp1, actual=c1, passed=c1 == exp1))

        # Case 2: text() and html() callback (i, origText) on single & multiple elements
        page.click("#btn-cb1")
        page.click("#btn-cb2")
        c2 = page.evaluate("""() => {
            $('.note').text(function (i, origText) {
                return '[' + i + ']' + origText;
            });
            const notes = Array.from(document.querySelectorAll('.note')).map(el => el.textContent);
            return {
                cbText: $('#cb-text').text(),
                cbHtml: $('#cb-html').html(),
                cbHtmlBoldCount: document.querySelectorAll('#cb-html b').length,
                notes
            };
        }""")
        exp2 = {
            "cbText": "旧文本: 原文本段落 新文本: Hello world! (index: 0)",
            "cbHtml": "旧 html: 原 <em>HTML</em> 段落 新 html: Hello <b>world!</b> (index: 0)",
            "cbHtmlBoldCount": 1,
            "notes": ["[0]条目A", "[1]条目B"],
        }
        cases.append(dict(name="set_text_and_html_callbacks", expected=exp2, actual=c2, passed=c2 == exp2))

        # Case 3: attr() single attribute setter
        page.click("#btn-attr1")
        c3 = page.evaluate("({ href: $('#doc-link').attr('href'), title: $('#doc-link').attr('title') })")
        exp3 = {"href": "https://api.jquery.com/category/manipulation/", "title": "旧标题"}
        cases.append(dict(name="set_attr_single", expected=exp3, actual=c3, passed=c3 == exp3))

        # Case 4: attr() multi-attribute object setter
        page.click("#btn-attr2")
        c4 = page.evaluate("({ href: $('#doc-link').attr('href'), title: $('#doc-link').attr('title') })")
        exp4 = {"href": "https://api.jquery.com", "title": "jQuery 官方文档"}
        cases.append(dict(name="set_attr_multiple_object", expected=exp4, actual=c4, passed=c4 == exp4))

        # Case 5: attr() callback (i, origValue)
        page.click("#btn-attr3")
        c5 = page.evaluate("({ href: $('#doc-link').attr('href') })")
        exp5 = {"href": "https://api.jquery.com/attr/0"}
        cases.append(dict(name="set_attr_callback", expected=exp5, actual=c5, passed=c5 == exp5))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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