代码之家  ›  专栏  ›  技术社区  ›  Ricardo Rocha

TypeScript:将类型属性添加到HtmlElement

  •  0
  • Ricardo Rocha  · 技术社区  · 6 年前

    我有以下TypeScript代码:

    let script: HTMLElement = document.createElement("script");
    script.appendChild(document.createTextNode(`
      {
        "json": "property"
      }
    `));
    script.id = 'appContextModel';
    document.body.appendChild(script);
    

    我得到以下错误:

    未捕获的语法错误:意外的标记:

    我想是因为脚本变量没有 type application/json 当我试图附加到身体上 HTMLElement ,编译器正在检索错误。

    我要找的是一种添加 type="application/json" 属性,仅使用TypeScript。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Heretic Monkey goproxy.dev    6 年前

    要向htmlement添加属性,只需调用 setAttribute function of the element

    let script: HTMLElement = document.createElement("script");
    script.appendChild(document.createTextNode(`
      {
        "json": "property"
      }
    `));
    script.id = 'appContextModel';
    script.setAttribute('type', 'application/json');
    document.body.appendChild(script);
    

    或者,在这种情况下,只需设置属性:

    script.type = 'application/json';
    

    请注意,在将代码直接写入 script