动态创建的脚本未执行
Dynamically created script not executing
我正在添加一个脚本标记,以及一堆其他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]);
}
};
当您以这种方式将它推送到DOM中时,它将不会执行。你会使用jQuery吗?它将执行它:
$('#reportContainer').append('<script type="text/javascript">alert(123);</script>');
您从ajax调用中得到的是纯文本或XML,可以作为HTML片段插入DOM,但出于安全原因,所有javascript代码都被明确禁止。有很多选择可以解决这种情况—从提取responseText中的部分和使用eval方法(不推荐,不好的做法)到使用jQuery。加载方法。
相关文章:
- 如果返回的数据是javascript,$.ajax会自动执行脚本吗
- 如果条件匹配,则停止执行脚本
- 加载服务器端渲染的React组件后执行脚本
- 量角器使用ElementArrayFinder执行脚本怪异
- 在selenium python中执行脚本
- 仅当脚本在视口中时执行脚本
- Chrome扩展:加载窗口后执行脚本
- FireFox扩展对TinyMCE编辑器执行脚本注入
- HTML表单-按'时执行脚本;输入',无需提交
- 当超出范围时,延迟执行脚本Jquery(或SetTimeOut)BUT
- 在执行脚本之前,请查看对象是否未定义
- 如何在整个网页加载后执行脚本
- 多次执行脚本的 jQuery
- 从另一个文件执行脚本
- 从单独的.php文件中执行<脚本>
- 如何防止执行脚本但在 DOM 中显示它
- 在 Mac 上的 Firebug 中继续执行脚本的快捷方式是什么?
- 文档.写入脚本内部不执行脚本
- 在页面加载之前在 ajax 请求的页面上执行脚本
- 如何对包含在父 html 中的子 html 文件执行脚本