蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery 教程目录 40章
jQuery / LEARN BY DOING

jQuery 选择器

核对元素、#id、.class 三大基础选择器,12 种常用进阶/自定义选择器(含 :first 与 :first-child 差异及奇偶行),以及独立 .js 文件拆分实践。

学完这一章,你能够

  • 核对元素、#id、.class 三大基础选择器,12 种常用进阶/自定义选择器(含 :first 与 :first-child 差异及奇偶行),以及独立 .js 文件拆分实践。

jQuery 选择器概览与三大基础选择器

jQuery 选择器允许开发者以统一语法定位单个 HTML 元素或整组元素。它基于元素的标签名、`id`、`class`、类型、属性及属性值进行匹配,在复用标准 CSS 选择器的同时扩展了 `:first`、`:button`、`:even`、`:odd` 等自定义选择器,且全部以 `$()` 开头。

元素选择器 `$('p')` 按标签名选取页面中所有对应元素。本站离线 Chromium 实测:点击 `#btn-hide-p` 后,区块内两段 `<p>`(`#ep1`、`#ep2`)计算 `display` 均变为 `none`,而同区块 `<div id="ed1">` 保持 `block`。

`#id` 选择器 `$('#test')` 通过 HTML 元素的 `id` 属性定位唯一节点(规范要求同一文档内 `id` 不重复)。点击 `#btn-hide-id` 后,`#test` 变为 `none`,同区块普通段落 `#keep-id` 保持 `block`。

`.class` 选择器 `$('.test')` 按类名选取所有携带该类的元素,不限标签类型。点击 `#btn-hide-class` 后,带 `class="test"` 的 `<h3 id="ch1">` 与 `<p id="cp1">` 同时隐藏为 `none`,无该类的 `#cp2` 保持 `block`。

常用进阶与自定义选择器对照

除基础三类外,日常开发还高频使用通配、当前元素、组合类、位置过滤、属性过滤、表单按钮及表格斑马纹选择器。本站离线 Chromium 逐项实测了全部 12 种选择器:特别注意 `$('ul li:first')` 仅返回文档中首个 `<ul>` 的第一个 `<li>`(`['u1l1']`),而 `$('ul li:first-child')` 会匹配每个 `<ul>` 的首个 `<li>`(`['u1l1', 'u2l1']`);`$('a[target!="_blank"]')` 会同时匹配 `target="_self"` 及未设 `target` 的 `<a>`(`['a-self', 'a-no-target', 'a-no-href']`);`$(':button')` 同时命中 `<button>` 与 `<input type="button">` 共 5 项且排除文本输入框;`$('tr:even')` 与 `$('tr:odd')` 按 0 基索引分别选中 `['r0', 'r2', 'r4']` 与 `['r1', 'r3']`(提示:jQuery 3.4+ 已弃用 `:first`/`:even`/`:odd` 等位置伪类,建议工程中逐步改用 `.first()` 或 `.filter()`)。

在独立 .js 文件中维护 jQuery 函数

教程示例为了紧凑常将脚本直接写在 `<head>` 中,但当站点包含多个页面时,应把业务 jQuery 函数抽离到独立的外部 `.js` 文件(如 `my_jquery_functions.js`),并在引入 jQuery 库之后通过 `<script src="my_jquery_functions.js"></script>` 加载,以利于多页复用与浏览器缓存。本站离线实验使用 `data:` URI 模拟外部脚本按序加载,确认其在 `$` 定义完成后正常绑定所有按钮点击事件(`__externalLoaded === true`)。

常用 jQuery 选择器语法与离线实测对照表

选择器语法匹配作用离线实测结果
$("*")选取文档中的所有元素实测匹配节点总数 > 20
$(this)选取当前触发事件的 HTML 元素点击 #btn-self 后自身变为 display: none
$("p.intro")选取 class 为 intro 的 <p> 元素仅命中 ['intro-p'],排除 div.intro
$("p:first")选取文档中第一个 <p> 元素仅命中首个段落 ['ep1']
$("ul li:first")选取第一个 <ul> 的第一个 <li>仅命中 ['u1l1']
$("ul li:first-child")选取每个 <ul> 的第一个 <li>命中两个列表首项 ['u1l1', 'u2l1']
$("[href]")选取所有带有 href 属性的元素命中 ['a-blank', 'a-self', 'a-no-target']
$("a[target='_blank']")选取 target 属性等于 _blank 的 <a>仅命中 ['a-blank']
$("a[target!='_blank']")选取 target 属性不等于 _blank 的 <a>命中 ['a-self', 'a-no-target', 'a-no-href']
$(":button")选取所有 <button> 与 type=button 的 <input>命中 4 个 button 与 in-btn,排除 in-txt
$("tr:even")选取 0 基偶数索引的 <tr> 行命中 ['r0', 'r2', 'r4']
$("tr:odd")选取 0 基奇数索引的 <tr> 行命中 ['r1', 'r3']

运行元素/#id/.class、12 种进阶选择器与外部脚本拆分离线实验

含完整源码 · 235 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery Chapter 5 (selectors)."""
import base64
import json
from playwright.sync_api import sync_playwright

MINI_JQ = r"""
(function (global) {
  function queryJQ(selector) {
    if (selector === ":button") {
      return Array.from(document.querySelectorAll("button, input[type='button']"));
    }
    const mNotAttr = selector.match(/^([a-zA-Z0-9_-]*)\[([a-zA-Z0-9_-]+)!=['"]([^'"]*)['"]\]$/);
    if (mNotAttr) {
      const base = mNotAttr[1] || "*";
      const attr = mNotAttr[2];
      const val = mNotAttr[3];
      return Array.from(document.querySelectorAll(base)).filter(function (el) {
        return el.getAttribute(attr) !== val;
      });
    }
    if (selector.endsWith(":first")) {
      const base = selector.slice(0, -":first".length);
      const list = Array.from(document.querySelectorAll(base));
      return list.length ? [list[0]] : [];
    }
    if (selector.endsWith(":even")) {
      const base = selector.slice(0, -":even".length);
      return Array.from(document.querySelectorAll(base)).filter(function (_, idx) { return idx % 2 === 0; });
    }
    if (selector.endsWith(":odd")) {
      const base = selector.slice(0, -":odd".length);
      return Array.from(document.querySelectorAll(base)).filter(function (_, idx) { return idx % 2 === 1; });
    }
    return Array.from(document.querySelectorAll(selector));
  }

  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(queryJQ(selector));
    return new JQ([]);
  }
  $.fn = JQ.prototype;
  $.fn.jquery = "3.7.1-offline-lab";
  global.$ = global.jQuery = $;
})(window);
"""

EXTERNAL_JS = """
$(document).ready(function () {
  window.__externalLoaded = true;
  $("#btn-hide-p").click(function () { $("#sec-el p").hide(); });
  $("#btn-hide-id").click(function () { $("#test").hide(); });
  $("#btn-hide-class").click(function () { $(".test").hide(); });
  $("#btn-self").click(function () { $(this).hide(); });
});
""".strip()

EXTERNAL_DATA_URI = "data:text/javascript;base64," + base64.b64encode(EXTERNAL_JS.encode("utf-8")).decode("ascii")

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>jQuery 选择器离线实验</title>
  <script>{MINI_JQ}</script>
  <script id="ext-fn-script" src="{EXTERNAL_DATA_URI}"></script>
</head>
<body>
  <section id="sec-el">
    <p id="ep1">元素段落 1</p>
    <p id="ep2">元素段落 2</p>
    <div id="ed1">保留 div</div>
    <button id="btn-hide-p" type="button">隐藏 p</button>
  </section>

  <section id="sec-id">
    <p id="test">唯一 ID 段落</p>
    <p id="keep-id">普通段落</p>
    <button id="btn-hide-id" type="button">隐藏 #test</button>
  </section>

  <section id="sec-cls">
    <h3 id="ch1" class="test">标题带 .test</h3>
    <p id="cp1" class="test">段落带 .test</p>
    <p id="cp2">无 .test 段落</p>
    <button id="btn-hide-class" type="button">隐藏 .test</button>
  </section>

  <section id="sec-more">
    <button id="btn-self" type="button">隐藏自身</button>
    <p id="intro-p" class="intro">带 intro 的段落</p>
    <div id="intro-div" class="intro">带 intro 的 div</div>
    <ul id="ul1">
      <li id="u1l1">L1-1</li>
      <li id="u1l2">L1-2</li>
    </ul>
    <ul id="ul2">
      <li id="u2l1">L2-1</li>
      <li id="u2l2">L2-2</li>
    </ul>
    <a id="a-blank" href="#b" target="_blank">新窗口链接</a>
    <a id="a-self" href="#s" target="_self">当前窗口链接</a>
    <a id="a-no-target" href="#n">无 target 链接</a>
    <a id="a-no-href">无 href 锚点</a>
    <input id="in-btn" type="button" value="输入按钮">
    <input id="in-txt" type="text" value="文本框">
    <table id="zebra">
      <tr id="r0"><td>0</td></tr>
      <tr id="r1"><td>1</td></tr>
      <tr id="r2"><td>2</td></tr>
      <tr id="r3"><td>3</td></tr>
      <tr id="r4"><td>4</td></tr>
    </table>
  </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_DOC, wait_until="load")

            # Case 1: Element, #id, and .class selectors via real button clicks
            page.locator("#btn-hide-p").click()
            page.locator("#btn-hide-id").click()
            page.locator("#btn-hide-class").click()
            act1 = page.evaluate(
                """() => ({
                    el_panel: ["ep1", "ep2", "ed1"].map(id => getComputedStyle(document.getElementById(id)).display),
                    id_panel: ["test", "keep-id"].map(id => getComputedStyle(document.getElementById(id)).display),
                    cls_panel: ["ch1", "cp1", "cp2"].map(id => getComputedStyle(document.getElementById(id)).display)
                })"""
            )
            exp1 = {
                "el_panel": ["none", "none", "block"],
                "id_panel": ["none", "block"],
                "cls_panel": ["none", "none", "block"],
            }
            cases.append(dict(name="element_id_class_selectors", passed=(act1 == exp1), expected=exp1, actual=act1))

            # Case 2: $("*"), $(this), $("p.intro"), $("p:first"), $("ul li:first") vs $("ul li:first-child")
            page.locator("#btn-self").click()
            act2 = page.evaluate(
                """() => ({
                    star_gt_20: $("*").length > 20,
                    this_hidden: getComputedStyle(document.getElementById("btn-self")).display,
                    p_intro: $("p.intro").elements.map(e => e.id),
                    p_first: $("p:first").elements.map(e => e.id),
                    ul_li_first: $("ul li:first").elements.map(e => e.id),
                    ul_li_first_child: $("ul li:first-child").elements.map(e => e.id)
                })"""
            )
            exp2 = {
                "star_gt_20": True,
                "this_hidden": "none",
                "p_intro": ["intro-p"],
                "p_first": ["ep1"],
                "ul_li_first": ["u1l1"],
                "ul_li_first_child": ["u1l1", "u2l1"],
            }
            cases.append(dict(name="structural_and_this_selectors", passed=(act2 == exp2), expected=exp2, actual=act2))

            # Case 3: Attribute selectors, :button, tr:even, tr:odd
            act3 = page.evaluate(
                """() => ({
                    href_ids: $("[href]").elements.map(e => e.id),
                    target_blank: $("a[target='_blank']").elements.map(e => e.id),
                    target_not_blank: $("a[target!='_blank']").elements.map(e => e.id),
                    button_ids: $(":button").elements.map(e => e.id),
                    tr_even: $("tr:even").elements.map(e => e.id),
                    tr_odd: $("tr:odd").elements.map(e => e.id)
                })"""
            )
            exp3 = {
                "href_ids": ["a-blank", "a-self", "a-no-target"],
                "target_blank": ["a-blank"],
                "target_not_blank": ["a-self", "a-no-target", "a-no-href"],
                "button_ids": ["btn-hide-p", "btn-hide-id", "btn-hide-class", "btn-self", "in-btn"],
                "tr_even": ["r0", "r2", "r4"],
                "tr_odd": ["r1", "r3"],
            }
            cases.append(dict(name="attribute_button_zebra_selectors", passed=(act3 == exp3), expected=exp3, actual=act3))

            # Case 4: External script separation & load order
            act4 = page.evaluate(
                """() => ({
                    external_loaded: window.__externalLoaded === true,
                    has_src_attr: document.getElementById("ext-fn-script").hasAttribute("src")
                })"""
            )
            exp4 = {"external_loaded": True, "has_src_attr": True}
            cases.append(dict(name="external_js_separation", passed=(act4 == exp4), expected=exp4, actual=act4))
        finally:
            browser.close()

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


if __name__ == "__main__":
    main()
在离线 Chromium 中核对三大基础选择器隐藏效果、:first 与 :first-child 匹配差异、属性/按钮/奇偶行精确 ID 列表,以及外部脚本按序初始化。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a906.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

$('ul li:first') 只取整个匹配集合中的第 1 个 <li>(仅 1 个元素),而 $('ul li:first-child') 匹配作为其父元素首个子节点的每个 <li>,因此每个 <ul> 都会命中 1 项。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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