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

运行 jQuery 选择器、事件、动画、DOM、尺寸、遍历与本地回环 AJAX 综合实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-examples.py
explore-examples.py670 行
"""Offline Playwright Chromium lab for jQuery Ch 31: examples (comprehensive interactive showcase)."""
import http.server
import json
import socketserver
import threading
from playwright.sync_api import sync_playwright

AJAX_HTML = '<div id="whole"><p id="part">Local AJAX Fragment</p><span id="extra">Extra</span></div>'


class LoopbackHandler(http.server.BaseHTTPRequestHandler):
    def log_message(self, fmt, *args):
        return

    def do_GET(self):
        if self.path == "/":
            body = HTML_DOC.encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        elif self.path == "/snippet.html":
            body = AJAX_HTML.encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        elif self.path == "/api/get":
            body = json.dumps({"method": "GET", "status": "ok", "msg": "hello-get"}).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.end_headers()

    def do_POST(self):
        length = int(self.headers.get("Content-Length", "0"))
        raw = self.rfile.read(length).decode("utf-8")
        if self.path == "/api/post":
            body = json.dumps({"method": "POST", "received": raw}).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.end_headers()


HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery 综合实例离线实验</title>
<style>
  #dim-box {
    width: 120px;
    height: 60px;
    padding: 10px;
    border: 2px solid #333;
    margin: 5px;
    box-sizing: content-box;
    background-color: rgb(255, 0, 0);
  }
  #anim-box {
    position: relative;
    left: 0px;
    width: 50px;
    height: 50px;
    opacity: 1;
  }
  .blue { color: blue; }
  .important { font-weight: bold; }
</style>
</head>
<body>
  <section id="sec-sel">
    <button id="btn-self">Hide Self</button>
    <p class="p-item">P1</p>
    <p class="p-item test">P2</p>
    <div id="test">ID Target</div>
  </section>

  <section id="sec-events">
    <button id="ev-btn">Event Button</button>
    <input id="ev-input" type="text" value="initial">
  </section>

  <section id="sec-fx">
    <div id="fx-box" style="display:block; opacity:1; height:40px;">FX</div>
    <div id="anim-box">ANIM</div>
  </section>

  <section id="sec-dom">
    <p id="dom-p">Hello <b>World</b></p>
    <input id="dom-in" type="text" value="alice">
    <a id="dom-link" href="https://example.org" title="orig">Link</a>
    <ul id="dom-list"><li class="keep">One</li><li class="del">Two</li></ul>
    <div id="dom-cls">Class Box</div>
    <div id="dim-box">Dim</div>
  </section>

  <section id="sec-trav">
    <div id="grandparent">
      <div id="parent">
        <span id="sib-a">A</span>
        <span id="target-span">B</span>
        <span id="sib-c">C</span>
        <em id="sib-d">D</em>
        <strong id="sib-e">E</strong>
      </div>
    </div>
  </section>

  <section id="sec-ajax">
    <div id="load-whole"></div>
    <div id="load-part"></div>
  </section>

  <canvas id="particles" width="120" height="60"></canvas>

  <script>
    // Compact offline jQuery-compatible API covering selectors, events, effects, DOM, CSS, dimensions, traversal, AJAX
    function JQ(els) {
      this.els = Array.isArray(els) ? els : (els ? [els] : []);
      this.length = this.els.length;
    }
    function $(sel) {
      if (sel instanceof JQ) return sel;
      if (typeof sel === 'string') {
        if (sel.trim().startsWith('<')) {
          const tpl = document.createElement('template');
          tpl.innerHTML = sel.trim();
          return new JQ(Array.from(tpl.content.childNodes));
        }
        return new JQ(Array.from(document.querySelectorAll(sel)));
      }
      return new JQ(sel);
    }

    JQ.prototype.hide = function() { this.els.forEach(e => { e.style.display = 'none'; }); return this; };
    JQ.prototype.show = function() { this.els.forEach(e => { e.style.display = 'block'; }); return this; };
    JQ.prototype.toggle = function() {
      this.els.forEach(e => { e.style.display = getComputedStyle(e).display === 'none' ? 'block' : 'none'; });
      return this;
    };
    JQ.prototype.fadeOut = function() { this.els.forEach(e => { e.style.opacity = '0'; e.style.display = 'none'; }); return this; };
    JQ.prototype.fadeIn = function() { this.els.forEach(e => { e.style.display = 'block'; e.style.opacity = '1'; }); return this; };
    JQ.prototype.fadeToggle = function() {
      this.els.forEach(e => {
        if (getComputedStyle(e).display === 'none') { e.style.display = 'block'; e.style.opacity = '1'; }
        else { e.style.opacity = '0'; e.style.display = 'none'; }
      });
      return this;
    };
    JQ.prototype.fadeTo = function(op) { this.els.forEach(e => { e.style.display = 'block'; e.style.opacity = String(op); }); return this; };
    JQ.prototype.slideUp = function() { this.els.forEach(e => { e.dataset.slide = 'up'; e.style.display = 'none'; }); return this; };
    JQ.prototype.slideDown = function() { this.els.forEach(e => { e.dataset.slide = 'down'; e.style.display = 'block'; }); return this; };
    JQ.prototype.slideToggle = function() {
      this.els.forEach(e => {
        if (getComputedStyle(e).display === 'none') { e.dataset.slide = 'down'; e.style.display = 'block'; }
        else { e.dataset.slide = 'up'; e.style.display = 'none'; }
      });
      return this;
    };

    const queues = new WeakMap();
    JQ.prototype.animate = function(props, cb) {
      this.els.forEach(e => {
        if (!queues.has(e)) queues.set(e, []);
        queues.get(e).push({ props, cb });
        const step = queues.get(e)[0];
        if (!e.dataset.animating) {
          this._runStep(e);
        }
      });
      return this;
    };
    JQ.prototype._runStep = function(e) {
      const q = queues.get(e) || [];
      if (!q.length) { delete e.dataset.animating; return; }
      e.dataset.animating = '1';
      const cur = q[0];
      Object.entries(cur.props).forEach(([k, v]) => {
        if (v === 'toggle') {
          e.style.display = getComputedStyle(e).display === 'none' ? 'block' : 'none';
        } else if (typeof v === 'string' && v.startsWith('+=')) {
          const delta = parseFloat(v.slice(2));
          const base = parseFloat(getComputedStyle(e)[k]) || 0;
          e.style[k] = (base + delta) + 'px';
        } else {
          e.style[k] = String(v);
        }
      });
      q.shift();
      if (typeof cur.cb === 'function') cur.cb.call(e);
      if (q.length) this._runStep(e);
      else delete e.dataset.animating;
    };
    JQ.prototype.stop = function(clearQueue, jumpToEnd) {
      this.els.forEach(e => {
        if (clearQueue) queues.set(e, []);
        if (jumpToEnd) e.dataset.jumped = '1';
        delete e.dataset.animating;
      });
      return this;
    };

    ['click', 'dblclick', 'mouseenter', 'mouseleave', 'mousedown', 'mouseup', 'focus', 'blur'].forEach(ev => {
      JQ.prototype[ev] = function(fn) {
        if (!fn) { this.els.forEach(e => e.dispatchEvent(new Event(ev, { bubbles: true }))); return this; }
        this.els.forEach(e => e.addEventListener(ev, fn));
        return this;
      };
    });
    JQ.prototype.hover = function(fnIn, fnOut) { return this.mouseenter(fnIn).mouseleave(fnOut); };

    JQ.prototype.text = function(val) {
      if (val === undefined) return this.els[0] ? this.els[0].textContent : '';
      this.els.forEach((e, i) => { e.textContent = typeof val === 'function' ? val(i, e.textContent) : val; });
      return this;
    };
    JQ.prototype.html = function(val) {
      if (val === undefined) return this.els[0] ? this.els[0].innerHTML : '';
      this.els.forEach((e, i) => { e.innerHTML = typeof val === 'function' ? val(i, e.innerHTML) : val; });
      return this;
    };
    JQ.prototype.val = function(val) {
      if (val === undefined) return this.els[0] ? this.els[0].value : '';
      this.els.forEach(e => { e.value = val; });
      return this;
    };
    JQ.prototype.attr = function(k, v) {
      if (typeof k === 'object') {
        Object.entries(k).forEach(([ak, av]) => this.attr(ak, av));
        return this;
      }
      if (v === undefined) return this.els[0] ? this.els[0].getAttribute(k) : null;
      this.els.forEach((e, i) => {
        const nv = typeof v === 'function' ? v(i, e.getAttribute(k)) : v;
        e.setAttribute(k, nv);
      });
      return this;
    };
    function toNodes(arg) {
      if (arg instanceof JQ) return arg.els;
      if (arg instanceof Node) return [arg];
      const tpl = document.createElement('template');
      tpl.innerHTML = String(arg);
      return Array.from(tpl.content.childNodes);
    }
    JQ.prototype.append = function(...args) {
      this.els.forEach(e => args.forEach(a => toNodes(a).forEach(n => e.appendChild(n))));
      return this;
    };
    JQ.prototype.prepend = function(...args) {
      this.els.forEach(e => args.reverse().forEach(a => toNodes(a).reverse().forEach(n => e.insertBefore(n, e.firstChild))));
      return this;
    };
    JQ.prototype.after = function(...args) {
      this.els.forEach(e => args.forEach(a => toNodes(a).forEach(n => e.parentNode.insertBefore(n, e.nextSibling))));
      return this;
    };
    JQ.prototype.before = function(...args) {
      this.els.forEach(e => args.forEach(a => toNodes(a).forEach(n => e.parentNode.insertBefore(n, e))));
      return this;
    };
    JQ.prototype.remove = function(filter) {
      this.els.forEach(e => { if (!filter || e.matches(filter)) e.remove(); });
      return this;
    };
    JQ.prototype.empty = function() { this.els.forEach(e => { e.innerHTML = ''; }); return this; };
    JQ.prototype.addClass = function(c) {
      const cls = c.trim().split(/\s+/);
      this.els.forEach(e => e.classList.add(...cls));
      return this;
    };
    JQ.prototype.removeClass = function(c) {
      const cls = c.trim().split(/\s+/);
      this.els.forEach(e => e.classList.remove(...cls));
      return this;
    };
    JQ.prototype.toggleClass = function(c) {
      this.els.forEach(e => e.classList.toggle(c));
      return this;
    };
    JQ.prototype.css = function(k, v) {
      if (typeof k === 'object') {
        Object.entries(k).forEach(([ck, cv]) => this.css(ck, cv));
        return this;
      }
      if (v === undefined) return this.els[0] ? getComputedStyle(this.els[0])[k] : '';
      this.els.forEach(e => { e.style[k] = v; });
      return this;
    };
    JQ.prototype.width = function(v) {
      const e = this.els[0];
      if (v !== undefined) { this.els.forEach(el => { el.style.width = v + 'px'; }); return this; }
      if (e === window) return window.innerWidth;
      if (e === document) return document.documentElement.scrollWidth;
      const cs = getComputedStyle(e);
      return parseFloat(cs.width);
    };
    JQ.prototype.height = function(v) {
      const e = this.els[0];
      if (v !== undefined) { this.els.forEach(el => { el.style.height = v + 'px'; }); return this; }
      if (e === window) return window.innerHeight;
      if (e === document) return document.documentElement.scrollHeight;
      const cs = getComputedStyle(e);
      return parseFloat(cs.height);
    };
    JQ.prototype.innerWidth = function() {
      const e = this.els[0];
      const cs = getComputedStyle(e);
      return parseFloat(cs.width) + parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight);
    };
    JQ.prototype.innerHeight = function() {
      const e = this.els[0];
      const cs = getComputedStyle(e);
      return parseFloat(cs.height) + parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom);
    };
    JQ.prototype.outerWidth = function(incMargin) {
      const e = this.els[0];
      const cs = getComputedStyle(e);
      return e.offsetWidth + (incMargin ? parseFloat(cs.marginLeft) + parseFloat(cs.marginRight) : 0);
    };
    JQ.prototype.outerHeight = function(incMargin) {
      const e = this.els[0];
      const cs = getComputedStyle(e);
      return e.offsetHeight + (incMargin ? parseFloat(cs.marginTop) + parseFloat(cs.marginBottom) : 0);
    };

    JQ.prototype.parent = function() { return new JQ(this.els[0] ? [this.els[0].parentElement] : []); };
    JQ.prototype.parents = function() {
      const out = [];
      let p = this.els[0] && this.els[0].parentElement;
      while (p) { out.push(p); p = p.parentElement; }
      return new JQ(out);
    };
    JQ.prototype.parentsUntil = function(sel) {
      const out = [];
      let p = this.els[0] && this.els[0].parentElement;
      while (p && !p.matches(sel)) { out.push(p); p = p.parentElement; }
      return new JQ(out);
    };
    JQ.prototype.children = function() { return new JQ(this.els[0] ? Array.from(this.els[0].children) : []); };
    JQ.prototype.find = function(sel) { return new JQ(this.els[0] ? Array.from(this.els[0].querySelectorAll(sel)) : []); };
    JQ.prototype.siblings = function() {
      const e = this.els[0];
      return new JQ(e ? Array.from(e.parentElement.children).filter(n => n !== e) : []);
    };
    JQ.prototype.next = function() { return new JQ(this.els[0] && this.els[0].nextElementSibling ? [this.els[0].nextElementSibling] : []); };
    JQ.prototype.nextAll = function() {
      const out = [];
      let n = this.els[0] && this.els[0].nextElementSibling;
      while (n) { out.push(n); n = n.nextElementSibling; }
      return new JQ(out);
    };
    JQ.prototype.nextUntil = function(sel) {
      const out = [];
      let n = this.els[0] && this.els[0].nextElementSibling;
      while (n && !n.matches(sel)) { out.push(n); n = n.nextElementSibling; }
      return new JQ(out);
    };

    JQ.prototype.load = async function(urlExpr, cb) {
      const [url, frag] = urlExpr.split(/\s+/);
      const res = await fetch(url);
      const txt = await res.text();
      if (frag) {
        const tpl = document.createElement('template');
        tpl.innerHTML = txt;
        const found = tpl.content.querySelector(frag);
        this.els.forEach(e => { e.innerHTML = found ? found.outerHTML : ''; });
      } else {
        this.els.forEach(e => { e.innerHTML = txt; });
      }
      if (cb) cb(txt, res.ok ? 'success' : 'error');
      return this;
    };
    $.get = async function(url) {
      const res = await fetch(url);
      return await res.json();
    };
    $.post = async function(url, data) {
      const res = await fetch(url, { method: 'POST', body: new URLSearchParams(data).toString() });
      return await res.json();
    };
    window.$ = $;
  </script>
</body>
</html>
"""


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


def main():
    socketserver.TCPServer.allow_reuse_address = True
    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), LoopbackHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            try:
                page = browser.new_page(viewport={"width": 800, "height": 600})
                page.goto(f"http://127.0.0.1:{port}/", wait_until="load")

                # Case 1: Selectors, events, hide/show/toggle
                res1 = page.evaluate("""() => {
                    const log = [];
                    $('#btn-self').click(function() { $(this).hide(); log.push('click'); });
                    $('#ev-btn')
                      .dblclick(() => log.push('dblclick'))
                      .hover(() => log.push('enter'), () => log.push('leave'))
                      .mousedown(() => log.push('down'))
                      .mouseup(() => log.push('up'));
                    $('#ev-input').focus(() => log.push('focus')).blur(() => log.push('blur'));

                    $('#btn-self').click();
                    const selfHidden = $('#btn-self').css('display') === 'none';
                    $('.test').hide();
                    const classHidden = $('.test').css('display') === 'none';
                    $('#test').hide();
                    const idHidden = $('#test').css('display') === 'none';
                    $('p.p-item').hide();
                    const pHiddenCount = $('p.p-item').els.filter(e => getComputedStyle(e).display === 'none').length;

                    $('#ev-btn').dblclick().mouseenter().mouseleave().mousedown().mouseup();
                    $('#ev-input').focus().blur();

                    $('#test').show();
                    const shownAfterShow = $('#test').css('display') === 'block';
                    $('#test').toggle();
                    const hiddenAfterToggle = $('#test').css('display') === 'none';
                    return { selfHidden, classHidden, idHidden, pHiddenCount, shownAfterShow, hiddenAfterToggle, log };
                }""")
                exp1 = {
                    "selfHidden": True,
                    "classHidden": True,
                    "idHidden": True,
                    "pHiddenCount": 2,
                    "shownAfterShow": True,
                    "hiddenAfterToggle": True,
                    "log": ["click", "dblclick", "enter", "leave", "down", "up", "focus", "blur"],
                }
                cases.append(dict(
                    name="selectors_events_visibility",
                    expected=exp1,
                    actual=res1,
                    passed=(res1 == exp1),
                ))

                # Case 2: Fade, slide, animate (multi-css, relative, toggle, callback), stop
                res2 = page.evaluate("""() => {
                    const steps = [];
                    $('#fx-box').fadeOut();
                    const afterFadeOut = $('#fx-box').css('display');
                    $('#fx-box').fadeIn();
                    const afterFadeIn = $('#fx-box').css('opacity');
                    $('#fx-box').fadeTo(0.4);
                    const afterFadeTo = $('#fx-box').css('opacity');
                    $('#fx-box').fadeToggle();
                    const afterFadeToggle = $('#fx-box').css('display');

                    $('#fx-box').slideDown();
                    const afterSlideDown = $('#fx-box').css('display');
                    $('#fx-box').slideUp();
                    const afterSlideUp = $('#fx-box').css('display');
                    $('#fx-box').slideToggle();
                    const afterSlideToggle = $('#fx-box').css('display');

                    $('#anim-box')
                      .animate({ left: '+=50px', opacity: '0.5', width: '+=30px' }, () => steps.push('cb1'))
                      .animate({ height: 'toggle' }, () => steps.push('cb2'));
                    const animState = {
                      left: $('#anim-box').css('left'),
                      width: $('#anim-box').css('width'),
                      opacity: $('#anim-box').css('opacity'),
                      display: $('#anim-box').css('display'),
                    };
                    $('#anim-box').stop(true, true);
                    const stoppedJump = document.getElementById('anim-box').dataset.jumped === '1';
                    return { afterFadeOut, afterFadeIn, afterFadeTo, afterFadeToggle, afterSlideDown, afterSlideUp, afterSlideToggle, animState, steps, stoppedJump };
                }""")
                exp2 = {
                    "afterFadeOut": "none",
                    "afterFadeIn": "1",
                    "afterFadeTo": "0.4",
                    "afterFadeToggle": "none",
                    "afterSlideDown": "block",
                    "afterSlideUp": "none",
                    "afterSlideToggle": "block",
                    "animState": {"left": "50px", "width": "80px", "opacity": "0.5", "display": "none"},
                    "steps": ["cb1", "cb2"],
                    "stoppedJump": True,
                }
                cases.append(dict(
                    name="effects_fade_slide_animate_stop",
                    expected=exp2,
                    actual=res2,
                    passed=(res2 == exp2),
                ))

                # Case 3: DOM get/set/insert/remove, classes, css(), dimensions
                res3 = page.evaluate("""() => {
                    const origText = $('#dom-p').text();
                    const origHtml = $('#dom-p').html();
                    const origVal = $('#dom-in').val();
                    const origHref = $('#dom-link').attr('href');

                    $('#dom-p').text((i, old) => old + '!');
                    const newText = $('#dom-p').text();
                    $('#dom-in').val('bob');
                    $('#dom-link').attr({ href: 'https://example.org/jq', title: 'updated' });
                    $('#dom-link').attr('href', (i, old) => old + '/v2');

                    $('#dom-list').append('<li>End</li>', document.createElement('li'));
                    $('#dom-list').prepend('<li>Start</li>');
                    $('#dom-p').before('<span class="ins">Before</span>').after('<span class="ins">After</span>');
                    $('#dom-list li').remove('.del');
                    const countAfterFilterRemove = $('#dom-list li').length;
                    $('#dom-list').empty();
                    const countAfterEmpty = $('#dom-list li').length;

                    $('#dom-cls').addClass('blue important').removeClass('blue').toggleClass('active');
                    const clsList = Array.from(document.getElementById('dom-cls').classList).sort();

                    const origBg = $('#dim-box').css('backgroundColor');
                    $('#dim-box').css({ backgroundColor: 'rgb(0, 128, 0)', fontSize: '14px' });
                    const newBg = $('#dim-box').css('backgroundColor');

                    const dims = {
                      w: $('#dim-box').width(),
                      h: $('#dim-box').height(),
                      iw: $('#dim-box').innerWidth(),
                      ih: $('#dim-box').innerHeight(),
                      ow: $('#dim-box').outerWidth(),
                      oh: $('#dim-box').outerHeight(),
                      owm: $('#dim-box').outerWidth(true),
                      ohm: $('#dim-box').outerHeight(true),
                      winW: $(window).width(),
                      winH: $(window).height(),
                    };
                    $('#dim-box').width(200).height(90);
                    const resized = [$('#dim-box').width(), $('#dim-box').height()];
                    return {
                      origText, origHtml, origVal, origHref, newText,
                      newVal: $('#dom-in').val(),
                      newHref: $('#dom-link').attr('href'),
                      newTitle: $('#dom-link').attr('title'),
                      countAfterFilterRemove, countAfterEmpty, clsList,
                      origBg, newBg, dims, resized,
                    };
                }""")
                exp3 = {
                    "origText": "Hello World",
                    "origHtml": "Hello <b>World</b>",
                    "origVal": "alice",
                    "origHref": "https://example.org",
                    "newText": "Hello World!",
                    "newVal": "bob",
                    "newHref": "https://example.org/jq/v2",
                    "newTitle": "updated",
                    "countAfterFilterRemove": 4,
                    "countAfterEmpty": 0,
                    "clsList": ["active", "important"],
                    "origBg": "rgb(255, 0, 0)",
                    "newBg": "rgb(0, 128, 0)",
                    "dims": {
                        "w": 120, "h": 60, "iw": 140, "ih": 80,
                        "ow": 144, "oh": 84, "owm": 154, "ohm": 94,
                        "winW": 800, "winH": 600,
                    },
                    "resized": [200, 90],
                }
                cases.append(dict(
                    name="dom_html_attr_css_dimensions",
                    expected=exp3,
                    actual=res3,
                    passed=(res3 == exp3),
                ))

                # Case 4: Traversal (ancestors/descendants/siblings) + local loopback AJAX + canvas particles
                res4 = page.evaluate("""async () => {
                    const parentId = $('#target-span').parent().els[0].id;
                    const untilIds = $('#target-span').parentsUntil('#sec-trav').els.map(e => e.id);
                    const childIds = $('#parent').children().els.map(e => e.id);
                    const foundSpans = $('#grandparent').find('span').els.map(e => e.id);
                    const sibIds = $('#target-span').siblings().els.map(e => e.id);
                    const nextId = $('#target-span').next().els[0].id;
                    const nextAllIds = $('#target-span').nextAll().els.map(e => e.id);
                    const nextUntilIds = $('#target-span').nextUntil('#sib-e').els.map(e => e.id);

                    let loadCbStatus = '';
                    await $('#load-whole').load('/snippet.html', (txt, status) => { loadCbStatus = status; });
                    await $('#load-part').load('/snippet.html #part');
                    const getRes = await $.get('/api/get');
                    const postRes = await $.post('/api/post', { name: 'jquery', topic: 'ajax' });

                    // Canvas particle step verification
                    const cvs = document.getElementById('particles');
                    const ctx = cvs.getContext('2d');
                    const pts = [{ x: 10, y: 10, vx: 3, vy: 2 }, { x: 40, y: 20, vx: -2, vy: 1 }];
                    ctx.clearRect(0, 0, cvs.width, cvs.height);
                    pts.forEach(pt => {
                      pt.x += pt.vx; pt.y += pt.vy;
                      ctx.fillStyle = '#09f';
                      ctx.fillRect(pt.x, pt.y, 4, 4);
                    });
                    const px = Array.from(ctx.getImageData(13, 12, 1, 1).data);
                    return {
                      parentId, untilIds, childIds, foundSpans, sibIds, nextId, nextAllIds, nextUntilIds,
                      loadWholeText: $('#load-whole').text(),
                      loadPartText: $('#load-part').text(),
                      loadCbStatus, getRes, postRes,
                      particleMoved: [pts[0].x, pts[0].y],
                      particlePixelAlpha: px[3],
                    };
                }""")
                exp4 = {
                    "parentId": "parent",
                    "untilIds": ["parent", "grandparent"],
                    "childIds": ["sib-a", "target-span", "sib-c", "sib-d", "sib-e"],
                    "foundSpans": ["sib-a", "target-span", "sib-c"],
                    "sibIds": ["sib-a", "sib-c", "sib-d", "sib-e"],
                    "nextId": "sib-c",
                    "nextAllIds": ["sib-c", "sib-d", "sib-e"],
                    "nextUntilIds": ["sib-c", "sib-d"],
                    "loadWholeText": "Local AJAX FragmentExtra",
                    "loadPartText": "Local AJAX Fragment",
                    "loadCbStatus": "success",
                    "getRes": {"method": "GET", "status": "ok", "msg": "hello-get"},
                    "postRes": {"method": "POST", "received": "name=jquery&topic=ajax"},
                    "particleMoved": [13, 12],
                    "particlePixelAlpha": 255,
                }
                cases.append(dict(
                    name="traversal_and_local_ajax",
                    expected=exp4,
                    actual=res4,
                    passed=(res4 == exp4),
                ))
            finally:
                browser.close()
    finally:
        server.shutdown()
        server.server_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-examples-lab/explore-examples.py

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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