亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從執行的字符串中使用 VanillaJS 創建腳本元素

從執行的字符串中使用 VanillaJS 創建腳本元素

滄海一幻覺 2021-11-25 16:08:02
我得到字符串:'<script class="heyo">document.write("hello")<\/script>' 我必須用 VanillaJS 創建一個內聯腳本元素。有沒有辦法觸發腳本執行?有效但太復雜:const scriptString = '<script class="heyo">document.write("hello")<\/script>';document.body.insertAdjacentHTML('beforeend', scriptString);const pseudoScript = document.body.querySelector('.heyo');const newScriptEl = document.createElement('script');[...pseudoScript.attributes].forEach(attr => {    newScriptEl.setAttribute(attr.nodeName, attr.nodeValue);});newScriptEl.innerHTML = pseudoScript.text;document.body.append(newScriptEl);pseudoScript.remove();任何更好的想法表示贊賞。
查看完整描述

2 回答

?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

我會說這或多或少是最好的方法。它“復雜”有什么關系?


我唯一沒有改變的不是將原始腳本插入到“實時”頁面中,而是插入到一個單獨的元素中,這也有不硬編碼類名的優點:


const scriptString = '<script class="heyo">document.write("hello")<\/script>';


const tempDiv = document.createElement("div");

tempDiv.innerHtml = scriptString;

const pseudoScript = tempDiv.firstChild;


const newScriptEl = document.createElement('script');

// ...


查看完整回答
反對 回復 2021-11-25
?
四季花海

TA貢獻1811條經驗 獲得超5個贊

一個小解決方案,appendChild而不是insertAdjacentHTML:


var scriptElement = document.createElement("script");

var scriptCode = document.createTextNode("document.write('hello')");

scriptElement.appendChild(scriptCode); 


document.body.appendChild(scriptElement);


查看完整回答
反對 回復 2021-11-25
  • 2 回答
  • 0 關注
  • 184 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號