← 中文资源

简体中文版本

ARIA 反射属性替代 setAttribute

ariaInvalid、ariaLive 等状态在 Element 上有类型化反射属性,赋值就是编译期校验;写错的属性名直接编译报错,不用再拼字符串。

阅读英文原文

实现说明

ARIA 反射属性替代 setAttribute可以归结为函数 bindField、reportProblem、clearProblem。 返回值是携带 input 的对象。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 直接运行文件,输出会带上标签,比如 aria-invalid:——输出的每一行都能指回产生它的那次调用。

常见问题

bindField 会修改传入的参数吗?

不会。传入的任何东西都不会被写入,对共享数据调用是安全的。

「ARIA 反射属性替代 setAttribute」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

签名一览:function bindField(inputId: string, errorId: string)

核心语句

if (!(input instanceof HTMLInputElement) || !error) return null;
return { input, error };

代码示例

// ARIA states have typed reflection properties on Element: no setAttribute
// strings, and unknown attribute names fail to compile.
interface FieldRefs {
  input: HTMLInputElement;
  error: HTMLElement;
}

function bindField(inputId: string, errorId: string): FieldRefs | null {
  const input = document.getElementById(inputId);
  const error = document.getElementById(errorId);
  if (!(input instanceof HTMLInputElement) || !error) return null;
  return { input, error };
}

function reportProblem(field: FieldRefs, message: string): void {
  field.input.ariaInvalid = 'true';
  field.error.ariaLive = 'assertive';
  field.error.textContent = message;
}

function clearProblem(field: FieldRefs): void {
  field.input.ariaInvalid = 'false';
  field.error.textContent = '';
}

const field = bindField('email', 'email-error');
if (field) {
  reportProblem(field, 'Email is missing an @');
  console.log('aria-invalid:', field.input.ariaInvalid);
  clearProblem(field);
  console.log('aria-invalid:', field.input.ariaInvalid);
}