如何动态插入< script>页面加载后通过jQuery标记? [英] How to dynamically insert a <script> tag via jQuery after page load?
问题描述
我遇到了解决这个问题的问题。我首先尝试将脚本标记设置为字符串,然后使用jquery replaceWith()在页面加载后将它们添加到文档中:
I'm having problems getting this to work. I first tried setting my script tags as strings and then using jquery replaceWith() to add them to the document after page load:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
但是我在该var上得到了字符串文字错误。然后我尝试对字符串进行编码,如:
But I got string literal errors on that var. I then tried encoding the string like:
var a = '&left;script type="text/javascript">some script here<\/script>';
但是将其发送到 replaceWith()
输出只是该字符串到浏览器。
but sending that to replaceWith()
outputs just that string to the browser.
有人可以告诉我你将如何动态添加< script>
在页面加载后标记到浏览器中,理想情况下通过jQuery标记?
Can someone please let me know how you would go about dynamically adding a <script>
tag into the browser after page load, ideally via jQuery?
推荐答案
您可以将脚本放入单独的文件中,然后使用 $。getScript
加载并运行它。
You can put the script into a separate file, then use $.getScript
to load and run it.
示例:
$.getScript("test.js", function(){
alert("Running test.js");
});
这篇关于如何动态插入< script>页面加载后通过jQuery标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!