根据url显示/隐藏文本的javascript不起作用

根据url显示/隐藏文本的javascript不起作用,javascript,jquery,Javascript,Jquery,此代码应基于页面的url显示/隐藏文本,但不起作用: var pages = window.location.href; if(pages == "page1.html"){ //display page 1 text } else if(pages == "page2.html"){ //display page 2 text } 我在本地对它进行了测试,但不起作用,所以我使用JSFIDLE进行了测试,但不幸的是,每次保存JSFIDLE时,都会得到一个新的u

此代码应基于页面的url显示/隐藏文本,但不起作用:

    var pages = window.location.href;    
if(pages == "page1.html"){
    //display page 1 text
}
else if(pages == "page2.html"){
    //display page 2 text
}

我在本地对它进行了测试,但不起作用,所以我使用JSFIDLE进行了测试,但不幸的是,每次保存JSFIDLE时,都会得到一个新的url

更新

这是更新后的代码,我可以指定文件扩展名来运行它,但我只需要使用url来运行它:

<script>
var pages = window.location.href;    
if( pages.split('/').pop() === 'http://akecheta.com/free-blogger-templates/' ) {
    document.write('<b>Hello World 1</b>');
}
else if( pages.split('/').pop() === 'http://akecheta.com/free-blogger-templates/' ) {
    document.write('<b>Hello World 2</b>');
}
</script>

var pages=window.location.href;
如果(pages.split('/').pop()http://akecheta.com/free-blogger-templates/' ) {
编写('Hello World 1');
}
else if(pages.split('/').pop()='http://akecheta.com/free-blogger-templates/' ) {
编写('Hello World 2');
}
解决方案
它不起作用,因为在JSFIDLE
var页面中
“http://fiddle.jshell.net/_display/ “

尝试console.log并确保在需要时也对其进行修剪。。
对于page1.html等的情况。。您必须将其与完整/绝对路径进行比较,
href
的值通常是一个绝对URL,因此您必须使用
.indexOf()
,如下所示:

var pages = window.location.href;    
if(pages.indexOf("page1.html") > -1){
    //display page 1 text
}
else if(pages.indexOf("page2.html") > -1 ){
    //display page 2 text
}
或者,您可以使用
.split()
.pop()
,假设您的URL没有查询字符串:

if( pages.split('/').pop() === 'page1.html' ) {
//...
更新

使用绝对URL或其更大部分时,不需要使用
.split()
.pop()
。请记住,
split
创建一个数组,而
pop
获取该数组的最后一个元素。对于绝对URL,您将不需要此过程

var pages = window.location.href;    
if( pages.indexOf( 'http://akecheta.com/free-blogger-templates/' ) > -1 ) {
    document.write('<b>Hello World 1</b>');
}
else if( pages.indexOf( 'http://akecheta.com/free-blogger-templates/xx' ) > -1 ) {
    document.write('<b>Hello World 2</b>');
}
var pages=window.location.href;
如果(第页索引为http://akecheta.com/free-blogger-templates/' ) > -1 ) {
编写('Hello World 1');
}
else if(第页索引)http://akecheta.com/free-blogger-templates/xx' ) > -1 ) {
编写('Hello World 2');
}
如果您的URL为,则需要URL路径。因此,代码如下所示

var pages = location.pathname;    
if(pages == "/page1.html"){
  //display page 1 text
}
else if(pages == "/page2.html"){
   //display page 2 text
}

所以我测试了你的代码,它没有使用jquery,很好,但是有一个问题,如果没有具体的文件扩展名,我无法在url上使用它。假设我有(一个搜索引擎友好的url)并且只需要文本出现在该页面中,我该怎么做?我将用更新的代码编辑我的主题,这样你就可以了解我在说什么。查看更新的答案。我注意到您提供的两个绝对URL是相同的,因此当存在匹配的URL时,只有
if
then
部分将运行。不要忘记接受答案
iff
这很有用。我是否应该用其他内容替换“xx”?是的。我必须让它与众不同,否则你就不需要
else
子句了。