jQuery 设置
核对 jQuery text()、html()、val() 与 attr() 的基础赋值、对象批量设置以及 (index, origValue) 回调函数写入机制。
学完这一章,你能够
- 核对 jQuery text()、html()、val() 与 attr() 的基础赋值、对象批量设置以及 (index, origValue) 回调函数写入机制。
基础设置:text()、html() 与 val()
上一章用于读取的 `text()`、`html()` 与 `val()` 同样是写入方法:传入参数时即由读取切换为设置——`text(str)` 替换元素纯文本、`html(str)` 替换元素内部 HTML 结构、`val(str)` 更新表单控件的值。
本站离线 Chromium 实测依次点击三个按钮:`$('#test1').text('Hello world!')` 将文本更新为 `'Hello world!'`;`$('#test2').html('<b>Hello world!</b>')` 实际解析生成 `1` 个 `<b>` 子节点;`$('#test3').val('jQuery 教程')` 实时更新输入框的值。额外对照实验显示,若把 `'<b>不解析标签</b>'` 传给 `.text()`,浏览器会按纯文本转义展示,内部 `<b>` 节点数为 `0`,可有效防范非预期 HTML 注入。
内容写入的回调函数:(index, origText)
`text()`、`html()` 与 `val()` 均支持传入回调函数动态计算新值。回调接收两个参数:当前元素在匹配集合中的下标 `i`(从 `0` 开始),以及该元素原本的旧值 `origText`;函数的返回值将被写回该元素。本站实测对单元素执行回调后,`#cb-text` 变为 `'旧文本: 原文本段落 新文本: Hello world! (index: 0)'`,`#cb-html` 变为 `'旧 html: 原 <em>HTML</em> 段落 新 html: Hello <b>world!</b> (index: 0)'` 并生成 `1` 个 `<b>` 节点;对两个 `.note` 段落批量执行回调则按索引分别写入 `'[0]条目A'` 与 `'[1]条目B'`。
设置单个、多个属性与 attr() 回调
`attr()` 同样兼具设置与修改能力:传入两个参数 `attr(name, value)` 即可更新指定属性。本站实测点击按钮将链接 `href` 由 `'https://api.jquery.com'` 改为 `'https://api.jquery.com/category/manipulation/'`,且原有的 `title='旧标题'` 保持不受影响。
需要一次修改多项属性时,可向 `attr()` 传入键值对对象 `attr({ href: ..., title: ... })`。实测单次调用即可同时把 `href` 设为 `'https://api.jquery.com'` 并把 `title` 更新为 `'jQuery 官方文档'`。
`attr(name, function(i, origValue){ ... })` 同样支持回调形式,依据当前下标与原属性值动态拼接新值。本站实测在 `'https://api.jquery.com'` 基础上返回 `origValue + '/attr/' + i`,成功将目标链接的 `href` 更新为 `'https://api.jquery.com/attr/0'`。
离线 Chromium 实测 text()/html()/val()/attr() 直接写入、多属性对象与回调写入
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`.text()` 会把尖括号当作纯文本字符写入,不创建 `<b>` 标签,适合渲染用户输入以防 XSS 注入;`.html()` 会将字符串解析为真实 HTML 节点并插入 DOM,仅应对可信模板使用。