簡體   English   中英

使用jQuery將JavaScript添加到HTML頁面

[英]add javascript into a html page with jquery

我想添加一個javascript Google廣告,但無法使用jquery將javascript插入div中。 我嘗試使用此測試來模擬我的問題,該測試使用的是我在stackoverflow上發現的一些建議,但它不起作用。

我希望將<script type='text/javascript'>document.write('hello world');</script>插入div,並在tag_1和tag_2之間顯示“ hello world”。

這是代碼:

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

坦克為您的答案,

盧卡斯

請參閱我的答案: 動態插入的<script>標簽是否有效? 為什么您不能使用innerHTML (當傳遞HTML字符串時jQuery的函數會映射到它)來插入腳本元素。 在完全解析文檔后使用 document.write也會失敗。

要解決此問題,您將必須使用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); 

頁面加載完成后,您將無法使用document.write 相反,只需插入要寫入的內容。

<script type="text/javascript">
     $(function() { // This is equivalent to document.ready
         var str="hello world";
         $('#insert_here').append(str);
     });
</script>

我想出了一個很好的解決方案:

  1. 將您的Google Adsense代碼插入頁面的任何位置-例如,如果CMS僅允許您將其放在右側,然后粘貼在此處。
  2. display:none樣式將div環繞在它周圍
  3. 添加一些jquery代碼以將div移動到所需的位置。

由於javascript已經運行,因此將腳本塊移動到您希望的任何位置都沒有問題。

例如,如果您希望在整個博客中穿插2個Google廣告塊(例如在第1款之后和第4款之后),那么這是完美的。

這是一些示例代碼:

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

ps #content恰好是內容在我的CMS(方形空間)上開始的位置,因此您可以將其替換為CMS中的內容。 這很有效,並且不會破壞Google ToS。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM