Javascript 如果更改页面,则更改标签

Javascript 如果更改页面,则更改标签,javascript,php,html,Javascript,Php,Html,我有一些JavaScript代码,如果主页或索引(例如标签处)没有更改。但是如果我更改页面,例如在,则标签将替换为 这是我的代码: <div id="header" class="hide"><h1>this my title</h1></div> <script> if(window.URL === 'malaspulang.com'){ }else{ $('#header').empty(); $('#header').ht

我有一些JavaScript代码,如果主页或索引(例如标签处)没有更改。但是如果我更改页面,例如在,则标签将替换为

这是我的代码:

<div id="header" class="hide"><h1>this my title</h1></div>
<script>
if(window.URL === 'malaspulang.com'){

}else{

 $('#header').empty();
 $('#header').html('<h2>this my title</h2>');
}
</script>
在我的主页站点中,标签应该替换为我认为我的代码是正确的,但是我对这个代码感到很困惑。因此,如果有人能帮助我,我会很高兴:

注意:如果有人使用PHP编写代码,您可以告诉我:

使用header访问id

$('#header').empty();
$('#header').html('<h2>this my title</h2>');
使用$'header'而不是$'。header'按id选择,而不是按类选择。您不需要$'.header'.empty。

将$'.header'替换为$'header'

$'header'-目标元素的id属性为'header'

$'.header'-以类属性为“header”的元素为目标。

您的问题是您的元素没有定义类。如图所示:这是我的标题,它的id是“header”,而不是header的类。这意味着您的JavaScript需要调用“header”的id,而不是类

以下是将起作用的代码:

$'header.html'这是我的标题'

不要使用window.URL,请尝试使用window.location.href并写出完整的URL名称:http://malaspulang.com

您也可以试穿一下,可能是这样:

<div class="hide" id="header">
  <h1>this my title</h1>
</div>
<script>
   $(document).ready(function(){
      console.log(document.URL);//this optional , just display your link at now
      var uri= document.URL;
      if(uri == 'http://malaspulang.com/'){ //use full link from your site
      //do nothing , because logical true
      }else{
          $('#header').empty();
          $('#header').html('<h2>this my title</h2>');
      }
   });
</script>

希望这对你有所帮助

我真的不明白…但为什么不在索引中添加硬代码标签,以及其他?实际上我使用wordpress站点,这是为了在SEO 1第1页中设置SEO,对吗,这是我的dinamic代码@Swellarew,实际上我的类已准备好使用,抱歉,我不明白你想用它说什么。阅读@CyanCoding的答案。他解释得很好。在malaspulang.com上查看我的网站,在首页的页眉处查看徽标,搜索是的,我正在使用它。实际上这个类已经使用了是的,我正在使用它。实际上这个类已经使用了@Hatchwald,它仍然不工作吗?很多答案都是关于你是如何使用类而不是id的。我看到你改变了,但是如果它仍然不起作用,你可能需要添加更多的解释/更多的代码。是的,仍然不起作用:,好吧,也许我会做一些解释:嗯,身体和家,它们来自哪里?你能添加一些解释吗?呃,在这个jsfiddle上,如果link为true,则显示h2,如果为false?如何解释?@Hatchwald如果window.location.href等于您的主页,则返回true并显示h1标记。
if($("body").hasClass("home")) {
    // don't do anything.
} else{
    // fire your code.
}
<div class="hide" id="header">
  <h1>this my title</h1>
</div>
<script>
   $(document).ready(function(){
      console.log(document.URL);//this optional , just display your link at now
      var uri= document.URL;
      if(uri == 'http://malaspulang.com/'){ //use full link from your site
      //do nothing , because logical true
      }else{
          $('#header').empty();
          $('#header').html('<h2>this my title</h2>');
      }
   });
</script>