是否可以将内嵌javascript代码插入到另一个javascript/jquery代码中?
这个问题看起来有点傻。。。但我想知道是否有可能将内嵌javascript代码插入到另一个javascript代码中。让我们澄清一下: 我尝试放置一个google plus按钮,通过jquery将其附加如下:是否可以将内嵌javascript代码插入到另一个javascript/jquery代码中?,javascript,jquery,nested,append,inline-code,Javascript,Jquery,Nested,Append,Inline Code,这个问题看起来有点傻。。。但我想知道是否有可能将内嵌javascript代码插入到另一个javascript代码中。让我们澄清一下: 我尝试放置一个google plus按钮,通过jquery将其附加如下: jQuery('.gplus').append('<g:plusone annotation="inline"></g:plusone>'); jQuery('.gplus').append(''); 此按钮需要外部js才能正常工作。我想做的是插入外部js,这样做
jQuery('.gplus').append('<g:plusone annotation="inline"></g:plusone>');
jQuery('.gplus').append('');
此按钮需要外部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);
var gplusjs='code>
(function(){var po=document.createElement(“脚本”);
po.type=“text/javascript”;po.async=true;
po.src=”https://apis.google.com/js/plusone.js";
var s=document.getElementsByTagName(“脚本”)[0];
s、 parentNode.insertBefore(po,s);
})();
';
jQuery('#js').append(gplusjs);
其结果是将代码打印为HTML,但不解释为脚本。
这是可能的吗?我是个笨蛋?谢谢 您应该正常执行该代码:
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);
或者更容易:
$.getScript("https://apis.google.com/js/plusone.js");
这是因为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);
还要注意,JS中不存在多行字符串文字。实际上,您可以通过使用
\
@SLaks这不是一个多行字符串文字,这是一个转义新行字符的恶意攻击。@SLaks作为一个更进一步的旁白,它是无效的ES3,你知道ES5是否允许它吗?我已经尝试了两种解决方案,但控制台向我抛出了这个错误:不安全的JavaScript试图从带有URL域的框架访问带有URL的框架,协议和端口必须匹配。@Raynos-反斜杠+换行符,因为行继续符在中。