TypeScript:将type属性添加到HtmlElement [英] TypeScript: add type property to HtmlElement

查看:135
本文介绍了TypeScript:将type属性添加到HtmlElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下TypeScript代码:

I have the following TypeScript code:

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

我收到以下错误:

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

Uncaught SyntaxError: Unexpected token :

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

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.

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

What I'm looking for is a way to add the type="application/json" property to the script element, using only TypeScript.

推荐答案

要将属性添加到HTMLElment,只需调用

To add an attribute to an HTMLElment, simply call the 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);

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

Or, in this case, just set the property:

script.type = 'application/json';

请注意,将代码直接写入 script 元素时,需要考虑一些安全问题,尤其是在响应用户输入时.

Note that there are some security issues to consider when writing code directly into a script element, especially if in response to user input.

这篇关于TypeScript:将type属性添加到HtmlElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆