2010-08-06 77 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