我将一个脚本标记以及许多其他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]);
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句