jQuery 过滤
核对按位置筛选集合的 first()、last()、eq() 以及按条件匹配或排除的 filter() 与 not() 五个过滤方法。
学完这一章,你能够
- 核对按位置筛选集合的 first()、last()、eq() 以及按条件匹配或排除的 filter() 与 not() 五个过滤方法。
按位置与按条件缩小元素集合
当初始选择器匹配到一组元素时,可借助过滤方法进一步缩小操作范围。最常用的位置过滤方法包括 `first()`、`last()` 与 `eq()`,它们按节点在匹配集合中的顺序下标提取单个元素;而 `filter()` 与 `not()` 则根据选择器或判定函数保留或排除满足指定条件的元素子集。
位置过滤:first()、last() 与 eq()
`first()` 返回匹配集合中的第一个元素。本站离线 Chromium 在包含两个 `<div>`(`#d1` 含 `p#p0.intro` 与 `p#p1.url`,`#d2` 含 `p#p2.note` 与 `p#p3.url`)的页面上实测:`$('div p').first()` 精准命中首个 `<div>` 中的第一个段落 `['p#p0']`,将其背景设为黄色(`rgb(255, 255, 0)`),而同容器第二段 `#p1` 保持透明(`rgba(0, 0, 0, 0)`)。
`last()` 返回匹配集合中的最后一个元素。本站实测 `$('div p').last()` 选中末尾 `<div>` 内的最后一个段落 `['p#p3']`,并将其背景色更新为青色(`rgb(0, 255, 255)`)。
`eq(index)` 按从 0 开始的索引提取指定位置的元素(首个元素索引为 `0`,第二个为 `1`),并支持负索引从集合末尾倒数。本站实测:`$("p").eq(0)` 返回 `['p#p0']`,`$("p").eq(1)` 返回第二个段落 `['p#p1']`,`$("p").eq(-1)` 返回末尾 `['p#p3']`,而越界索引 `$("p").eq(10)` 返回空集合 `[]`。
条件过滤:filter() 与 not()
`filter(criteria)` 依据给定的选择器或回调函数筛选当前集合,不匹配的元素被剔除,匹配项保留为新集合。本站实测:`$("p").filter(".url")` 返回全部带有 `url` 类名的段落 `['p#p1', 'p#p3']`;传入索引回调 `(i) => i % 2 === 0` 则保留偶数下标项 `['p#p0', 'p#p2']`。
`not(criteria)` 语义与 `filter()` 相反,用于返回不满足指定标准的所有元素。本站实测 `$("p").not(".url")` 返回 `['p#p0', 'p#p2']`,与 `$("p").filter(".url")` 构成互不相交的严格补集(两集合元素数之和 `2 + 2 = 4` 等于全部 `<p>` 数量)。
在离线 Chromium 中实测 first()、last()、eq()、filter() 与 not() 五种集合过滤方法
展开查看收起
"""Offline Playwright Chromium lab for jQuery Chapter 25 (traversing-filtering)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>jQuery Filtering Lab</title></head>
<body>
<div id="d1" style="border: 1px solid black;">
<p id="p0" class="intro">第一个 div 的第一段</p>
<p id="p1" class="url">第一个 div 的第二段 (class="url")</p>
</div>
<div id="d2" style="border: 1px solid black;">
<p id="p2" class="note">第二个 div 的第一段</p>
<p id="p3" class="url">第二个 div 的第二段 (class="url")</p>
</div>
<script>
(function (global) {
function wrap(nodes) {
const list = Array.from(nodes);
return {
nodes: list,
length: list.length,
ids() {
return list.map(el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
},
css(prop, val) {
for (const el of list) el.style[prop] = val;
return this;
},
first() {
return wrap(list.length ? [list[0]] : []);
},
last() {
return wrap(list.length ? [list[list.length - 1]] : []);
},
eq(index) {
const idx = index < 0 ? list.length + index : index;
return wrap(idx >= 0 && idx < list.length ? [list[idx]] : []);
},
filter(criteria) {
if (typeof criteria === 'function') {
return wrap(list.filter((el, i) => criteria.call(el, i, el)));
}
return wrap(list.filter(el => el.matches(criteria)));
},
not(criteria) {
if (typeof criteria === 'function') {
return wrap(list.filter((el, i) => !criteria.call(el, i, el)));
}
return wrap(list.filter(el => !el.matches(criteria)));
}
};
}
global.$ = function (arg) {
if (arg === document) return { ready(fn) { fn(); } };
if (typeof arg === 'string') return wrap(document.querySelectorAll(arg));
return wrap([]);
};
})(window);
</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)
try:
page = browser.new_page(viewport={"width": 1000, "height": 700})
page.set_content(HTML_DOC)
c1 = page.evaluate("""() => {
const res = $("div p").first().css("backgroundColor", "yellow");
return {
matched: res.ids(),
p0_bg: getComputedStyle(document.getElementById("p0")).backgroundColor,
p1_bg: getComputedStyle(document.getElementById("p1")).backgroundColor
};
}""")
exp1 = {
"matched": ["p#p0"],
"p0_bg": "rgb(255, 255, 0)",
"p1_bg": "rgba(0, 0, 0, 0)",
}
cases.append({"name": "first_matched_element", "passed": c1 == exp1, "expected": exp1, "actual": c1})
c2 = page.evaluate("""() => {
const res = $("div p").last().css("backgroundColor", "cyan");
return {
matched: res.ids(),
p3_bg: getComputedStyle(document.getElementById("p3")).backgroundColor
};
}""")
exp2 = {
"matched": ["p#p3"],
"p3_bg": "rgb(0, 255, 255)",
}
cases.append({"name": "last_matched_element", "passed": c2 == exp2, "expected": exp2, "actual": c2})
c3 = page.evaluate("""() => ({
eq_0: $("p").eq(0).ids(),
eq_1: $("p").eq(1).ids(),
eq_neg1: $("p").eq(-1).ids(),
eq_out_of_range: $("p").eq(10).ids()
})""")
exp3 = {
"eq_0": ["p#p0"],
"eq_1": ["p#p1"],
"eq_neg1": ["p#p3"],
"eq_out_of_range": [],
}
cases.append({"name": "eq_zero_based_and_negative_index", "passed": c3 == exp3, "expected": exp3, "actual": c3})
c4 = page.evaluate("""() => ({
filter_url: $("p").filter(".url").ids(),
filter_even_index: $("p").filter((i) => i % 2 === 0).ids()
})""")
exp4 = {
"filter_url": ["p#p1", "p#p3"],
"filter_even_index": ["p#p0", "p#p2"],
}
cases.append({"name": "filter_matching_criteria", "passed": c4 == exp4, "expected": exp4, "actual": c4})
c5 = page.evaluate("""() => {
const kept = $("p").filter(".url").ids();
const excluded = $("p").not(".url").ids();
return {
not_url: excluded,
complement_count_matches_total: kept.length + excluded.length === $("p").length,
disjoint: kept.every(id => !excluded.includes(id))
};
}""")
exp5 = {
"not_url": ["p#p0", "p#p2"],
"complement_count_matches_total": True,
"disjoint": True,
}
cases.append({"name": "not_excluding_criteria", "passed": c5 == exp5, "expected": exp5, "actual": c5})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
eq() 使用 0 起始索引,eq(1) 选中第二个元素 p#p1,eq(-1) 倒数第一选中 p#p3;在同一集合和同一条件下,filter() 与 not() 返回互不相交的互补子集。