![](/img/trans.png)
[英]Typescript : Property 'data' dose not exist on 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.