示例工程 27-dom-web-types
27-dom-web-types/03-dataset-forms/src/main.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
export function readIndex(root: ParentNode): string {
const element = root.querySelector<HTMLElement>('[data-index]');
return element?.dataset['index'] ?? '(none)';
}
export function readName(root: ParentNode): string {
const form = root.querySelector<HTMLFormElement>('form');
if (form === null) return '(no-form)';
const value = new FormData(form).get('name');
return typeof value === 'string' ? value : '(none)';
}
export function run(log: (msg: string) => void = console.log, root?: ParentNode): string[] {
const scope = root ?? (typeof document === 'undefined' ? undefined : document);
if (scope === undefined) throw new Error('本示例需要浏览器环境');
const lines = [readIndex(scope), readName(scope)];
for (const line of lines) {
log(line);
}
return lines;
}