你如何执行动态加载的JavaScript块? [英] How do you execute a dynamically loaded JavaScript block?
问题描述
我正在一个网页,我正在做一个AJAX调用返回的HTML一大块像:
I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like:
<div>
<!-- some html -->
<script type="text/javascript">
/** some javascript */
</script>
</div>
我插入了整个事情到DOM,但JavaScript是没有运行。有没有一种方法来运行呢?
I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it?
一些细节:我无法控制什么是在脚本块(所以我不能将其更改为一个可以被称为功能),我只需要被执行的整个街区。我不能叫EVAL上的反应,因为JavaScript是HTML的一个更大的块中。我可以做一些正则表达式来分离出的JavaScript,然后调用的eval就可以了,但是这是pretty的难吃。任何人都知道一个更好的办法?
Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?
推荐答案
脚本通过设置元素的innerHTML属性添加不会被执行。尝试创建一个新的div,并设置其的innerHTML,然后将这个新的分区到DOM。例如:
Script added by setting the innerHTML property of an element doesn't get executed. Try creating a new div, setting its innerHTML, then adding this new div to the DOM. For example:
<html>
<head>
<script type='text/javascript'>
function addScript()
{
var str = "<script>alert('i am here');<\/script>";
var newdiv = document.createElement('div');
newdiv.innerHTML = str;
document.getElementById('target').appendChild(newdiv);
}
</script>
</head>
<body>
<input type="button" value="add script" onclick="addScript()"/>
<div>hello world</div>
<div id="target"></div>
</body>
</html>
这篇关于你如何执行动态加载的JavaScript块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!