2014-10-27 92 views
0

我想一個JavaScript僅在我的論壇的一個網頁的工作,所以我用這個代碼:加載JavaScript的只在一個網頁

if (window.location.href.indexOf('/u1') != -1) { 

但它也影響到像/ U11網頁,/ U12,/ U13 ,/ u14等。

我能做些什麼才能使代碼只在/ u1中工作?

回答

0

試試這個,我忽略了你使用乾淨的URL的事實。

//split url into an array separated by the/
    var url = window.location.href.split("/"); 

    //store the page that you want the script to execute on 
    var rightPage = "u1"; 



//if the last index of the url array equals the value of the rightPage 
//note: -1 is subtracted because array indexes start at 0 
if (url[url.length - 1] === rightPage) {//begin if then else 


//do something if the your on the rightPage 
alert("right"); 

} 
else{ 

//do something if you are not on rightPage 
alert(page.join("/")); 

}//end if then else 
+0

謝謝你,但它沒有工作,網頁它只是「U1」而不是「u1.html」看看http://nootroheroemas.foroweb.org/u1 – AlexTCGPro 2014-10-28 00:16:59

+0

非常感謝,它的工作原理完美:D,祝你有個愉快的日子^^ – AlexTCGPro 2014-10-28 00:31:17

+0

歡迎你的光臨,我可以幫忙 – 2014-10-28 00:34:16

0

這一個發現,如果有一個確切的段「U1」的URL裏面,但在href路徑不關心它的位置(這也會爲http://somewhere.com/one/two/three/u1/foo/bar返回true),但它很簡單應該夠了。

var segments = window.location.href.split("/"); 
var found = false; 
// You can also do this loop with index and count the position if needed 
for (var segment in segments){ 
    if (segment == "u1"){ 
     found = true; 
     break; 
    } 
} 
// do with found whatever you need below