是否可以将内嵌 javascript 代码插入到另一个 javascript/jquery 代码中?

Man*_*anu 1 javascript jquery nested append inline-code

这个问题看起来有点愚蠢......但我想知道是否可以将内联 javascript 代码插入到另一个 javascript 代码中。让我们说清楚:

我试图放置一个 google plus 按钮,通过 jquery 附加它,如下所示:

jQuery('.gplus').append('<g:plusone annotation="inline"></g:plusone>');
Run Code Online (Sandbox Code Playgroud)

这个按钮需要外部js才能正常工作。我想做的是插入外部js来执行以下操作:

var gplusjs = '
<script type="text/javascript">
  (function() {var po = document.createElement("script");
    po.type = "text/javascript"; po.async = true;
    po.src = "https://apis.google.com/js/plusone.js";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(po, s);
  })();
</script>';
jQuery('#js').append(gplusjs);
Run Code Online (Sandbox Code Playgroud)

其结果是将代码打印为 HTML,但不解释为脚本。这个有可能?我是个笨蛋吗?谢谢!

Ray*_*nos 9

那是因为 jQuery 附加和脚本不起作用。用老式的方式做

var gplusjs = '(function() {var po = document.createElement("script");po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(po, s);})();';
var script = document.createElement("script");
script.textContent = gplusjs;
document.head.appendChild(script);
Run Code Online (Sandbox Code Playgroud)

另请注意,JS 中不存在多行字符串文字。

  • 实际上,您可以通过使用“\​”转义每个换行符来创建多行字符串文字 (3认同)
  • @Raynos - 反斜杠 + 换行符作为行继续位于 [ECMAScript 262 第五版](http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262%205th%20edition% 12 月 20 日%202009.pdf)。 (3认同)