简体   繁体   English

将javascript添加到onDocumentReady问题

[英]Adding javascript to onDocumentReady issue

I have a div on my page defined as follows: 我的页面上有一个div定义如下:

<div id="scripts">
</div>

I want to dynamically change the contents of the div and load in some scripts using jQuery. 我想动态更改div的内容并使用jQuery加载一些脚本。 I am doing it like this: 我是这样做的:

$('#scripts').html('<script language="JavaScript">pn = "landing page"; '+
'cms_1 = "content"; '+
'cms_2 = "promotional "; '+
'cms_3 = "campaign"; '+
'cms_s = "blk:us:dc"; '+
'cms_env = "dev"; '+
'cms_country = "USA"; '+
'<\/script>');

This is in the document.Ready function. 这是在document.Ready函数中。 However, when I view the source after the page is loaded, the div appears empty and I do not see the script tags. 但是,当我在加载页面后查看源代码时,div显示为空,我看不到脚本标记。 I thought that the script wasn't getting added but when I add alert("done"); 我认为脚本没有被添加但是当我添加alert("done"); to the script. 到脚本。 I get the alert which tells me that the code is executed. 我收到警告,告诉我代码已执行。

Why can't I see the changes made when I view the source? 为什么我在查看源代码时看不到所做的更改? Is the Source html rendered before the document.ready function? Source html是否在document.ready函数之前呈现?

The html function from jquery internally uses the innerHTML property of the browser when available. 来自jquery的html函数在内部使用浏览器的innerHTML属性(如果可用)。 In general, script blocks inserted via innerHTML don't get executed almost in any browser. 通常,通过innerHTML插入的脚本块几乎不会在任何浏览器中执行。

Try creating a script tag with the content and appending it to the document instead, eg 尝试使用内容创建脚本标记,然后将其附加到文档中,例如

var script=document.createElement('script');
script.type='text/javascript';
script.html(...);

$("#scripts").append(script);

After seeing your motivation in the comment, I have to add : although you can later physically remove a script tag from the site, this won't have the effect of unloading its content (eg functions defined in the script). 在评论中看到你的动机之后,我必须补充一点:虽然你以后可以从网站上物理删除脚本标签,但这不会有卸载其内容的效果(例如脚本中定义的功能)。 The only way to achieve that without refreshing the page is to encapsulate the objects defined in it and delete them manually. 在不刷新页面的情况下实现该目的的唯一方法是封装在其中定义的对象并手动删除它们。 This is of course only possible if the content of the script was designed upfront in such a way. 当然,只有在脚本的内容以这种方式预先设计的情况下才有可能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM