Javascript 无法动态添加脚本节点

Javascript 无法动态添加脚本节点,javascript,jquery,Javascript,Jquery,我正在尝试使用以下代码附加节点 <html> <body> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script> $('body').append('<script>alert(\'foo\');</script>'); </script> </bod

我正在尝试使用以下代码附加
节点

<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
  $('body').append('<script>alert(\'foo\');</script>');
</script>
</body>
</html>
要添加一个已执行的字符串,但实际上添加了以下字符串

');

这里发生了什么?

您必须正确地转义这里的斜杠字符,并对foo使用双引号:

<html>
  <body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script>
      $('body').append('<script>alert("foo");<\/script>');
    </script>
  </body>
</html>

$('body').append('alert(“foo”);');
您必须在字符串中打断
,否则它将被视为
的结束标记

$('body').append('alert(\'foo\');');

因为它提前结束了脚本标记:可能重复
<html>
  <body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script>
      $('body').append('<script>alert("foo");<\/script>');
    </script>
  </body>
</html>
  $('body').append('<script>alert(\'foo\');</scr'+'ipt>');