简体   繁体   English

TypeScript:将type属性添加到HtmlElement

[英]TypeScript: add type property to HtmlElement

I have the following TypeScript code: 我有以下TypeScript代码:

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

And I'm getting the following error: 我收到以下错误:

Uncaught SyntaxError: Unexpected token : 未捕获到的SyntaxError:意外令牌:

I think because the script variable does not have the property type with value application/json when I try to append to the body that HTMLElement , the compiler is retrieving the error. 我认为,因为当我尝试将HTMLElement附加到正文时,脚本变量不具有值为application/json的属性type ,因此编译器正在检索错误。

What I'm looking for is a way to add the type="application/json" property to the script element, using only TypeScript. 我正在寻找的是一种仅使用TypeScript将type="application/json"属性添加到脚本元素的方法。

To add an attribute to an HTMLElment, simply call the setAttribute function of the element : 要将属性添加到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);

Or, in this case, just set the property: 或者,在这种情况下,只需设置属性:

script.type = 'application/json';

Note that there are some security issues to consider when writing code directly into a script element, especially if in response to user input. 请注意,将代码直接写入script元素时要考虑一些安全问题,尤其是在响应用户输入时。

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

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