2014-04-01 57 views
0

我有一个字符串在HTML应该后装入正文。评估一个后加载的脚本

var str = new String("<span>Hello</span><script>window.alert('hello');</script>"); 
    document.getElementsByTagName('body')[0].innerHTML=str; 

但警报没有来。所以我补充说:

for(i=0;scr=document.getElementsByTagName('body')[0].getElementsByTagName('script')[i];i++) { 
    eval(src.innerHTML); 
    }; 

但即使它不起作用。你能解决我的问题吗?

+0

'src'从哪里来? “scr”从哪里来? – chris97ong

+0

有了第一个解决方案,“hello”这个词最终在页面上出现了吗? – stUrb

回答

0
document.getElementsByTagName('body')[0].innerHTML="<span>Hello</span><script>window.alert('hello');<\/script>"; 
var alert_func = document.getElementsByTagName('script')[0].innerHTML 
if(alert_func.indexOf("alert") != -1) { 
    eval(alert_func); 
} 

此代码将首先设置<body>标签的innerHTML来<span>Hello</span><script>window.alert('hello');</script>。然后变量alert_func将存储<script>标签之间的内容。如果alert_func中有“alert”字样,我们将评估<script>标签之间的任何内容并发出警报。

+1

你也可以解释为什么这应该起作用吗?只是倾销一些代码行并不是很有帮助。 – nwellnhof