2015-04-12 61 views
0

我想调用<div>脚本,但它不起作用。热添加动态脚本标记div标记

例如,调用了alert(101),但未调用alert(201)alert(202)

<html> 
    <head> 
    </head> 
    <body> 
    <p>start</p> 
    <div id="abc"></div> 
    <p>end</p> 
    <script> 
     // append script (invoked!!) 
     var s = document.createElement('script'); 
     s.setAttribute('type', 'text/javascript'); 
     s.innerHTML = 'alert(101);'; 
     document.getElementById('abc').appendChild(s); 

     // append div (not works) 
     var d = document.createElement('div'); 
     // I'm going to try to add a div, script, multi tags. 
     // This data will be get via Ajax. 
     d.innerHTML = "<script type='text/javascript'>alert(201);<\/script><script type='text/javascript'>alert(202);<\/script>"; 
     document.getElementById('abc').appendChild(d); 
    </script> 
    </body> 
</html> 

你能告诉我一个解决方案吗?

+0

为什么你逃脱斜线''<\/script>? – jcubic

+0

@jcubic对不起,我不太明白。不使用转义时出错。 'SyntaxError:unterminated string literal' –

+0

尝试'''s.onload = function(){ alert(“202); };'' – styopdev

回答

0

这对我的作品

// append script (invoked!!) 
var s = document.createElement('script'); 
s.setAttribute('type', 'text/javascript'); 
s.innerHTML = 'alert(101);'; 
document.getElementById('abc').appendChild(s); 

// append div (not works) 
var d = document.createElement('div'); 
var s2 = document.createElement('script'); 
s2.innerText = 'alert(201)'; 
d.appendChild(s2); 
// I'm going to try to add a div, script, multi tags. 
// This data will be get via Ajax. 
// d.innerHTML = "<script type='text/javascript'>alert(201);<\/script><script type='text/javascript'>alert(202);<\/script>"; 
document.getElementById('abc').appendChild(d); 
+0

谢谢!它的工作。 –