繁体   English   中英

TypeScript:将type属性添加到HtmlElement

[英]TypeScript: add type property to HtmlElement

我有以下TypeScript代码:

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

我收到以下错误:

未捕获到的SyntaxError:意外令牌:

我认为,因为当我尝试将HTMLElement附加到正文时,脚本变量不具有值为application/json的属性type ,因此编译器正在检索错误。

我正在寻找的是一种仅使用TypeScript将type="application/json"属性添加到脚本元素的方法。

要将属性添加到HTMLElment中,只需调用元素setAttribute函数

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元素时要考虑一些安全问题,尤其是在响应用户输入时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM