我想一个JavaScript仅在我的论坛的一个网页的工作,所以我用这个代码:加载JavaScript的只在一个网页
if (window.location.href.indexOf('/u1') != -1) {
但它也影响到像/ U11网页,/ U12,/ U13 ,/ u14等。
我能做些什么才能使代码只在/ u1中工作?
我想一个JavaScript仅在我的论坛的一个网页的工作,所以我用这个代码:加载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
这一个发现,如果有一个确切的段“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
谢谢你,但它没有工作,网页它只是“U1”而不是“u1.html”看看http://nootroheroemas.foroweb.org/u1 – AlexTCGPro 2014-10-28 00:16:59
非常感谢,它的工作原理完美:D,祝你有个愉快的日子^^ – AlexTCGPro 2014-10-28 00:31:17
欢迎你的光临,我可以帮忙 – 2014-10-28 00:34:16