Skip to content

Examples (table)

Bhsd edited this page Apr 17, 2026 · 5 revisions

Other Languages

让表格可排序

展开

你可以让页面中的表格支持排序。此示例演示了 TableToken 的用法。

// Making a table sortable (main)
// 包含表格的页面内容
import type {TableToken} from 'wikiparser-node';
const content = `{| class="wikitable"
! Word
|-
| Foo
|-
| Bar
|}`,
	root = Parser.parse(content),
	table = root.querySelector<TableToken>('table');
if (table) {
	table.classList.add('sortable');
}
assert.equal(
	root,
	`{| class="wikitable sortable"
! Word
|-
| Foo
|-
| Bar
|}`,
);

向表格添加一行

展开

你可以在页面中的表格添加一行。此示例演示了 TableTokenTdToken.innerText 的用法。

// Adding a row to a table (main)
// 包含表格的页面内容
import type {TableToken} from 'wikiparser-node';
const content = `{|
! Rank !! Word
|-
| 1 | Foo
|-
| 2 | Bar
|}`,
	root = Parser.parse(content),
	table = root.querySelector<TableToken>('table'),
	rowCount = table?.getRowCount();
if (table) {
	// 在表格末尾插入一行空行
	table.insertTableRow(rowCount, undefined, '');
	table.getNthCell({row: rowCount, column: 0}).innerText = '3';
	table.getNthCell({row: rowCount, column: 1}).innerText = 'Baz';
}
assert.equal(
	root,
	`{|
! Rank !! Word
|-
| 1 | Foo
|-
| 2 | Bar
|-
|3
|Baz
|}`,
);

Clone this wiki locally