仅在一个网页中加载JavaScript

时间:2014-10-27 22:12:15

标签: javascript window href indexof

我希望JavaScript只能在我论坛的一个网页上使用,所以我使用了这段代码:

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

但它也会影响/ u11,/ u12,/ u13,/ u14等网页。

如何使代码仅在/ u1中起作用?

2 个答案:

答案 0 :(得分:0)

试试这个,我忽略了你使用干净网址的事实。

  //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

答案 1 :(得分:0)

这个人会发现url中是否有一个确切的段“u1”,但是不关心它在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