使用 jquery 将 javascript 添加到 html 页面中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3418041/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add javascript into a html page with jquery
提问by Lucas
I want to add a javascript google ad but I can't insert the javascript into the div using jquery. I try to simulate my problem with this test, which is using some advice I found on stackoverflow , but it does not work.
我想添加一个 javascript 谷歌广告,但我无法使用 jquery 将 javascript 插入到 div 中。我尝试用这个测试来模拟我的问题,它使用了我在 stackoverflow 上找到的一些建议,但它不起作用。
I want <script type='text/javascript'>document.write('hello world');</script>to be inserted in the div, and "hello world" be displayed between the tag_1 and tag_2.
我想<script type='text/javascript'>document.write('hello world');</script>插入到div中,在tag_1和tag_2之间显示“hello world”。
Here is the code :
这是代码:
<html>
    <head>
      <script type="text/javascript" src="jquery.js"></script>
      <script type="text/javascript">
         $(document).ready(function() {
         var str="<script type='text/javascript'>document.write('hello world');";
         str+="<";
         str+="/script>";
         $('#insert_here').append(str);
         });
      </script>
    </head>
    <body>
      tag_1<br/>
      <div id="insert_here">
      </div>
      tag_2<br/>
    </body>
</html>
Tanks for your answers,
坦克为您解答,
Lucas
卢卡斯
采纳答案by Dave Hilditch
I figured out a great solution:
我想出了一个很好的解决方案:
- Insert your Google Adsense code anywhere on your page - e.g. if your CMS only allows you to put this on the right hand side then stick it there.
 - Wrap a div around it with 
display:nonestyle - Add some jquery code to move the div to the location you desire.
 
- 将您的 Google Adsense 代码插入页面的任何位置 - 例如,如果您的 CMS 只允许您将其放在右侧,然后将其粘贴在那里。
 - 用
display:none样式将 div 包裹起来 - 添加一些 jquery 代码将 div 移动到您想要的位置。
 
Since the javascript has already run there is no problem then with moving the block of script to wherever you'd like it to be.
由于 javascript 已经运行,因此将脚本块移动到您想要的任何位置都没有问题。
e.g. if you wish to put 2 blocks of google adverts interspersed throughout your blog (say after paragraph 1 and after paragraph 4) then this is perfect.
例如,如果您希望在整个博客中穿插 2 块谷歌广告(例如在第 1 段之后和第 4 段之后),那么这是完美的。
Here's some example code:
下面是一些示例代码:
<div id="advert1" style="display:none">
<div class="advertbox advertfont">
    <div style="float:right;">
        <script type="text/javascript"><!--
        google_ad_client = "pub-xxxxxxxxxxxxxxxxx";
        /* Video box */
        google_ad_slot = "xxxxxxxxxxxxxxxxx"
        google_ad_width = 300;
        google_ad_height = 250;
        //-->
        </script>
        <script type="text/javascript"
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
    </div>
</div>
</div>
<script>
$(document).ready(function() {
$('#advert1').appendTo("#content p:eq(1)");
$('#advert1').css("display", "block");
});
</script>
p.s. #content happens to be where the content starts on my CMS (Squarespace) so you can replace that with whatever you have in your CMS. This works a treat and doesn't break Google ToS.
ps #content 恰好是内容在我的 CMS(Squarespace)上的开始位置,因此您可以将其替换为您的 CMS 中的任何内容。这很有效,并且不会破坏 Google ToS。
回答by Andy E
See my answer to Are dynamically inserted <script> tags meant to work?for why you can't use innerHTML, which jQuery's functions map to when passed a HTML string, to insert a script element. document.writewill also fail when used after the document has been fully parsed.
请参阅我对动态插入的 <script> 标签是否有效的回答?为什么你不能使用innerHTML来插入脚本元素,jQuery 的函数在传递 HTML 字符串时映射到它。 在文档完全解析后使用document.write也会失败。
To work around this, you will have to use DOM functions to insert an element into the div. Google ads are iframes, so it's usually a case of finding the iframe code and appending that instead.
要解决此问题,您必须使用 DOM 函数将元素插入到 div 中。Google 广告是 iframe,因此通常需要查找 iframe 代码并附加该代码。
要正确插入脚本元素,您需要使用 DOM 函数,例如:
var txt = 'alert("Hello");';
var scr = document.createElement("script");
scr.type= "text/javascript";
// We have to use .text for IE, .textContent for standards compliance.
if ("textContent" in scr)
    scr.textContent = txt;
else
    scr.text = txt;
// Finally, insert the script element into the div
document.getElementById("insert_here").appendChild(scr);
回答by Sean Vieira
You cannot use document.writeafter the page has finished loading.  Instead, simply insert the contents that you want to be written in.
document.write页面加载完成后无法使用。相反,只需插入您想要写入的内容。
<script type="text/javascript">
     $(function() { // This is equivalent to document.ready
         var str="hello world";
         $('#insert_here').append(str);
     });
</script>

