2010-05-17 22 views
10

我想在特定頁面上顯示特定消息。如果URL包含此操作,請使用Javascript

假設我要顯示在被稱爲「foo_page.html」東西頁面的名稱,

我怎樣才能做到這一點使用JavaScript?

+0

請提供更多詳細信息。 – SLaks 2010-05-17 15:39:35

回答

28

你可以這樣說:

if(document.URL.indexOf("foo_page.html") >= 0){ 
...show your message 
} 
+3

可能想要'> = 0'。 – Syntactic 2010-05-17 15:44:06

+0

好的地方,謝謝。編輯。 – GShenanigan 2010-05-17 15:44:45

1
var index = document.location.lastIndexOf("/"); 
var filename = document.location.substr(index); 

if(filename.indexOf("foo_page.html")>-1){ 
    alert("OK"); 
} 
1

您可以使用document.location弄清楚訪客所在的網址。

試試這個:

<script type="text/javascript"> 
var currentPage = document.location.href.substring(document.location.href.lastIndexOf("/")+1, document.location.href.length); 
</script> 

你「當前頁」變量現在應該包含你正在瀏覽的網頁的名稱。你可以用它來選擇一個動作。

0
var loc = window.location.pathname.split("/"), 
    size = loc.length 

    alert(loc[size]) 

給你最後一部分被「/」分開大部分時間的HTML,PHP或任何文件。但我會用你身體上的課程來認識你的位置。或者只是檢查你想要做什麼的元素是否存在於頁面上。在你執行這樣的功能之前

function example(element) { 
     if(getElementById(element).length) { 
      // now you are sure that a element exists on the page 
     }else{ 
     return false; //if not just do nothing 
     } 
    } 
    example("myId") 
+1

'loc [size-1]',或者只是:'var filename = location.pathname.split('/')。pop();'。 (爲什麼'.'在元素節點上?) – bobince 2010-05-17 16:18:39

+0

什麼是pop()在做什麼?長度來獲得數組的最後一塊。 thx爲tipp – meo 2010-05-17 16:35:37

相關問題