仅在一个网页中加载JavaScript

Load JavaScript in only one webpage

本文关键字:网页 加载 JavaScript 一个      更新时间:2023-09-26

我希望JavaScript只能在论坛的一个网页中工作,所以我使用了以下代码:

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

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

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

试试这个,我忽略了你使用干净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

这个函数会发现url中是否有一个精确的段"u1",但不关心它在href路径中的位置(对于http://somewhere.com/one/two/three/u1/foo/bar),但它很简单,应该足够了。

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