2011-09-26 115 views
0

我想在帖子內部放置一個javascript(adsense)代碼(不在上面或後面)。它將是一個HTML頁面。調用函數來執行javascript代碼

有什麼辦法可以把我的adsense代碼放在外部的Js文件中,我會用一個函數來顯示它。 AdSense代碼看起來像

<script type="text/javascript"><!-- 
google_ad_client = "pub-xxxxxxxxxxxxxxxx"; 
google_ad_host = "pub-xxxxxxxxxxxxxxxx"; 
google_ad_slot = "xxxxxxxxxx"; 
google_ad_width = 336; 
google_ad_height = 280; 
//--> 
</script> 
<script type="text/javascript" 
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

所以,如果我調用一個函數CallMe()無論我已經使用,其功能就會開始顯示廣告。今後如果我想用另一個代碼替換廣告代碼,那麼我不想去每個帖子並將其替換。我只會從js文件中替換adcode。

我是新手,剛開始學習JavaScript,所以我真的不知道它是否可以完成。

有什麼建議嗎?

回答

1

創建文件名爲AdSense.js用下面的代碼:

google_ad_client = "pub-xxxxxxxxxxxxxxxx"; 
google_ad_host = "pub-xxxxxxxxxxxxxxxx"; 
google_ad_slot = "xxxxxxxxxx"; 
google_ad_width = 336; 
google_ad_height = 280; 
function ApplyAdSense() { 
    var oScript = document.createElement("script"); 
    oScript.type = "text/javascript"; 
    oScript.src = "http://pagead2.googlesyndication.com/pagead/show_ads.js"; 
    document.getElementsByTagName("head")[0].appendChild(oScript); 
} 

現在,只要你想在你的代碼的AdSense,第一個包含文件:

<script type="text/javascript" src="AdSense.js"></script> 

然後調用函數:

<script type="text/javascript"> 
    ApplyAdSense(); 
</script> 

這樣,直到你調用函數什麼也沒有發生..你也可以評論函數內的代碼,以禁止所有網站的AdSense。

+0

非常感謝回答..讓我先試試這個..我會讓你知道它的工作與否.. –

+0

對不起..沒有工作 –

+0

嗯..你得到什麼錯誤?你可以在JavaScript控制檯中看到嗎? –

0

無論您希望廣告展示在哪裏,放置此代碼(假設您有一個名爲CallMe的功能)。

<some html> 
     <script type="text/javascript">CallMe();</script> 
    </some html> 
+0

沒有。 callMe()只是一個例子...我需要把代碼放在JS文件中嗎? –