如何动态插入

我在让它发挥作用时遇到问题。我首先尝试将脚本标签设置为字符串,然后使用 jquery ReplaceWith() 在页面加载后将它们添加到文档中:

var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);

但是我在该变量上遇到了字符串文字错误。然后我尝试对字符串进行编码,如下所示:

var a = '&left;script type="text/javascript"&gt;some script here&lt;\/script&gt;';

但将其发送到 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);

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>';

but sending that to replaceWith() outputs just that string to the browser.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

梦在深巷 2024-10-03 01:09:45

您可以将脚本放入单独的文件中,然后使用 $.getScript 加载并运行它。

例子:

$.getScript("test.js", function(){
    alert("Running test.js");
});

You can put the script into a separate file, then use $.getScript to load and run it.

Example:

$.getScript("test.js", function(){
    alert("Running test.js");
});
冷情 2024-10-03 01:09:45

请尝试以下操作:

<script type="text/javascript">
// Use any event to append the code
$(document).ready(function() 
{
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "http://scriptlocation/das.js";
    // Use any selector
    $("head").append(s);
});

http://api.jquery.com/append

Try the following:

<script type="text/javascript">
// Use any event to append the code
$(document).ready(function() 
{
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "http://scriptlocation/das.js";
    // Use any selector
    $("head").append(s);
});

http://api.jquery.com/append

转身泪倾城 2024-10-03 01:09:45

这是使用现代(2014)JQuery 执行此操作的正确方法:

$(function () {
  $('<script>')
    .attr('type', 'text/javascript')
    .text('some script here')
    .appendTo('head');
})

或者如果您确实想替换 div,您可以这样做:

$(function () {
  $('<script>')
    .attr('type', 'text/javascript')
    .text('some script here')
    .replaceAll('#someelement');
});

Here's the correct way to do it with modern (2014) JQuery:

$(function () {
  $('<script>')
    .attr('type', 'text/javascript')
    .text('some script here')
    .appendTo('head');
})

or if you really want to replace a div you could do:

$(function () {
  $('<script>')
    .attr('type', 'text/javascript')
    .text('some script here')
    .replaceAll('#someelement');
});
五里雾 2024-10-03 01:09:45

更简单的方法是:

$('head').append('<script type="text/javascript" src="your.js"></script>');

也可以使用这种形式来加载css。

A simpler way is:

$('head').append('<script type="text/javascript" src="your.js"></script>');

You can also use this form to load css.

故人的歌 2024-10-03 01:09:45

这个答案在技术上与 jcoffland 的回答相似或相同。
我刚刚添加了一个查询来检测脚本是否已经存在。
我需要这个,因为我在一个带有几个模块的 Intranet 网站上工作,其中一些模块共享脚本或自带脚本,但这些脚本不需要每次都再次加载。我在生产环境中使用这个代码片段已有一年多了,它的效果就像一个魅力。对自己评论:是的,我知道,询问函数是否存在会更正确......:-)

if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
    $('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}

This answer is technically similar or equal to what jcoffland answered.
I just added a query to detect if a script is already present or not.
I need this because I work in an intranet website with a couple of modules, of which some are sharing scripts or bring their own, but these scripts do not need to be loaded everytime again. I am using this snippet since more than a year in production environment, it works like a charme. Commenting to myself: Yes I know, it would be more correct to ask if a function exists... :-)

if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
    $('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}
無心 2024-10-03 01:09:45

这是一种更清晰的方法 - 不需要 jQuery - 添加一个脚本作为 的最后一个子元素:

document.body.innerHTML +='<script src="mycdn.js"><\/script>'

但是如果你想添加加载脚本使用 火箭危险品的方法

注意:它将取消声明的事件侦听器。

Here is a much clearer way — no need for jQuery — which adds a script as the last child of <body>:

document.body.innerHTML +='<script src="mycdn.js"><\/script>'

But if you want to add and load scripts use Rocket Hazmat's method.

Note: it willl cancel declared event listeners.

别低头,皇冠会掉 2024-10-03 01:09:45

示例:

var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);

它应该可以工作。我试过了;相同的结果。但是当我使用这个时:

var length = 1;
var html = "";
for (var i = 0; i < length; i++) {
    html += '<div id="codeSnippet"></div>';
    html += '<script type="text/javascript">';
    html += 'your script here';
    html += '</script>';
}
$('#someElement').replaceWith(a);

这对我有用。

编辑:我忘记了 #someelement (顺便说一句,由于约定,我可能想使用 #someElement

这里最重要的是 += 所以添加了 html 而不是更换。

如果不起作用请发表评论。我愿意帮助你!

Example:

var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);

It should work. I tried it; same outcome. But when I used this:

var length = 1;
var html = "";
for (var i = 0; i < length; i++) {
    html += '<div id="codeSnippet"></div>';
    html += '<script type="text/javascript">';
    html += 'your script here';
    html += '</script>';
}
$('#someElement').replaceWith(a);

This worked for me.

Edit: I forgot the #someelement (btw I might want to use #someElement because of conventions)

The most important thing here is the += so the html is added and not replaced.

Leave a comment if it didn't work. I'd like to help you out!

世俗缘 2024-10-03 01:09:45

有一种解决方法听起来更像是一种 hack,我同意这不是最优雅的方法,但 100% 有效:

假设你的 AJAX 响应类似于

<b>some html</b>
<script>alert("and some javscript")

请注意,我故意跳过了结束标签。 然后在加载上述内容的脚本中,执行以下操作:

$.ajax({
    url: "path/to/return/the-above-js+html.php",
    success: function(newhtml){
        newhtml += "<";
        newhtml += "/script>";
        $("head").append(newhtml);
    }
});

只是不要问我为什么:-)这是我通过绝望的几乎随机试验和失败而遇到的事情之一。

我没有关于它如何工作的完整建议,但有趣的是,如果您将结束标签附加在一行中,它将不起作用。

在这样的时候,我感觉我已经成功除以零了。

There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:

Say your AJAX response is something like

<b>some html</b>
<script>alert("and some javscript")

Note that I've skipped the closing tag on purpose. Then in the script that loads the above, do the following:

$.ajax({
    url: "path/to/return/the-above-js+html.php",
    success: function(newhtml){
        newhtml += "<";
        newhtml += "/script>";
        $("head").append(newhtml);
    }
});

Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.

I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.

In times like these, I feel like I've successfully divided by zero.

↘人皮目录ツ 2024-10-03 01:09:45

如果您尝试运行一些动态生成的 JavaScript,那么使用 eval 会稍微好一些。然而,JavaScript 是一种动态语言,您确实不需要它。

如果脚本是静态的,那么 Rocket 的 getScript-suggestion 就是最佳选择。

If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval. However, JavaScript is such a dynamic language that you really should not have a need for that.

If the script is static, then Rocket's getScript-suggestion is the way to go.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文