热门动态地附加带有脚本标签的div标签

时间:2015-04-12 09:15:44

标签: javascript html

我想用<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>

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

1 个答案:

答案 0 :(得分: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);