2010-08-06 80 views
2

我的問題是我想添加JavaScript到HTML頁面,感謝安迪E,我找到了方式add my JavaScript into a html page and be executed。但現在我的問題是,所有的頁面被JavaScript覆蓋。有人知道如何做同樣的事情,但沒有用JavaScript覆蓋頁面,要添加到代碼或東西來改變:)?動態添加JavaScript覆蓋HTML頁面視圖(不是代碼)

  • 我不想重新加載頁面,因爲我不希望用戶看到頁面的兩倍,如果頁面包含了很多東西,這將是非常不方便的事情。

這是一個短代碼,告訴你我的問題:(我改變了廣告代碼,因爲它不是我的,所以我不能把它放在這個公共場所)

<html> 
    <head> 
     <script type="text/javascript" src="jquery.js"></script> 
     <script type="text/javascript"> 
     $(document).ready(function() {; 
      var correct_div = document.getElementById('ad_468x60'); 

      var sTag1 = document.createElement("script"); 
      sTag1.type = "text/javascript"; 
      sTag1.text = "<!--\ngoogle_ad_client = \"pub-123456789\";\ngoogle_alternate_color = \"FFFFFF\";\ngoogle_ad_width = 468;\ngoogle_ad_height = 60;\ngoogle_ad_format = \"468x60_as\";\ngoogle_ad_channel =\"123456789\";\ngoogle_color_border = \"FFFFC6\";\ngoogle_color_bg = \"FFFFFF\";\ngoogle_color_link = \"000000\";\ngoogle_color_url = \"666666\";\ngoogle_color_text = \"333333\";\n//-->" 
      correct_div.appendChild(sTag1); 

      var sTag2 = document.createElement("script"); 
      sTag2.type = "text/javascript"; 
      sTag2.src = "http://google_ad_url.js"; 
      correct_div.appendChild(sTag2) 
     }); 
     </script> 
    </head> 

    <body> 
     <div> 
     "This text appears and disappears after the ad is displayed" 
     </div> 

     <div id="ad_468x60"> 
     <!-- The JavaScript come here --> 
     </div> 
    </body> 
</html> 

編輯:我可以使用iframe來做到這一點嗎?

回答

2

有幾件事你可以做。

  • 將腳本添加到空的iframe中。這將導致iframe內容被覆蓋document.write。您需要將iframe設置爲適當的尺寸。

  • 用你自己的方法覆蓋document.write函數。事情是這樣的:

    // Create a closure to keep the old document.write private 
    (function() { 
        var oldDW = document.write; 
        document.write = function (s) { 
         // Document not parsed yet, allow document.write: 
         if (document.readyState != "complete") 
          oldDW.call(document, s); 
         // Dangerous use, switch to innerHTML instead: 
         else   
          document.getElementById("ad_468x60").innerHTML = s; 
        } 
    })(); 
    

    Example

正如你現在知道,是否存在由document.write()的第二種方法也不會削減它寫任何腳本元素 - 你必須編寫更復雜的例程來解析出腳本元素,並使用document.createElement()來代替。

+0

好吧,安迪,再次感謝你的所有答案。谷歌廣告似乎本身在iframe中,你認爲這會是一個問題嗎?我們正在嘗試第一個解決方案 – Lucas 2010-08-09 17:24:59

+0

@Lucas:這不應該是一個問題。如果* document.write()*只是將一個iframe元素寫入頁面,那麼使用重寫方法可能會更容易一些。 – 2010-08-09 17:27:05

+0

似乎它不寫入元素,但這裏是谷歌代碼,它會更簡單: http://pagead2.googlesyndication.com/pagead/show_ads.js 所以我嘗試重寫方法 – Lucas 2010-08-09 19:03:28

2

如果代碼使用document.write,它將覆蓋該頁面。對此,你無能爲力。

+0

是的,看着谷歌JS它使用document.write ...無論如何非常感謝,我們現在確信我們可以放棄這種做法。 – Lucas 2010-08-06 19:50:03

0

您應該在這裏使用getScript函數。

+0

好的,但我是一個jQuery新手...我讀了你給我的jQuery鏈接,但我看不到我應該如何在這裏使用它 – Lucas 2010-08-07 01:26:35