gpt4 book ai didi

javascript - 动态创建的脚本未执行

转载 作者:行者123 更新时间:2023-12-03 12:25:44 25 4
gpt4 key购买 nike

我正在将一个脚本标记以及一堆其他 html 附加到我当前的文档(从 ajax 调用中检索)。由于某种原因,脚本没有运行

//Response handling function
function(responseText){
document.getElementById('reportContainer').insertAdjacentHTML('afterbegin',responseText);
}

responseText 内容示例:

<h2>You are <em class="won">victorious</em>!</h2>
<h3>Earnings</h3>
...
<script>
alert('dgd');
</script>

所有 html 都被应用到文档中,包括脚本,但它没有运行,我没有弹出此警报。可能是什么原因造成的?

最佳答案

检查以下代码片段并调用该函数

var newEle = document.querySelector("#reportContainer");
exec_body_scripts(newEle);

功能

exec_body_scripts = function(body_el) {
// Finds and executes scripts in a newly added element's body.
// Needed since innerHTML does not run scripts.
//
// Argument body_el is an element in the dom.

function nodeName(elem, name) {
return elem.nodeName && elem.nodeName.toUpperCase() ===
name.toUpperCase();
};

function evalScript(elem) {
var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
head = document.getElementsByTagName("head")[0] ||
document.documentElement,
script = document.createElement("script");

script.type = "text/javascript";
try {
// doesn't work on ie...
script.appendChild(document.createTextNode(data));
} catch(e) {
// IE has funky script nodes
script.text = data;
}

head.insertBefore(script, head.firstChild);
head.removeChild(script);
};

// main section of function
var scripts = [],
script,
children_nodes = body_el.childNodes,
child,
i;

for (i = 0; children_nodes[i]; i++) {
child = children_nodes[i];
if (nodeName(child, "script" ) &&
(!child.type || child.type.toLowerCase() === "text/javascript")) {
scripts.push(child);
}
}

for (i = 0; scripts[i]; i++) {
script = scripts[i];
if (script.parentNode) {script.parentNode.removeChild(script);}
evalScript(scripts[i]);
}
};

关于javascript - 动态创建的脚本未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24222074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com