jQuery在首页中隐藏/显示div

时间:2018-06-23 12:34:53

标签: javascript jquery

我有一个Google自定义搜索,我想在链接为www.mywebsite.com时在主页上显示广告,而在链接为https://www.mywebsite.com/?q=时隐藏广告,我该怎么做?谢谢

$(function(){

    var currPath = window.location.pathname; 

  $('.path').text('Current path is : '+ currPath);
  if(currPath == 'https://www.mywebsite.com'){ 
    $('.sidebar').show(); 
  }else {}

})

1 个答案:

答案 0 :(得分:0)

pathname属性不包含域,因此您必须将其测试为/(根)...

下面,我使用了完整的href属性并将其拆分以获取域(这可能对您有用...) 的字符串,与pathname输出 而没有/前缀 的内容相同。

$(function(){

  var currHref = window.location.href; 
  console.log(currHref);
  
  var currDomain = currHref.split("/").slice(0,3).join("/");
  console.log(currDomain);
  
  var currPath = currHref.split("/").slice(3).join("/");
  console.log(currPath);
  
  
  $('.domain').text('Current domain is : '+ currDomain);
  $('.path').text('Current path is : /'+ currPath);
  
  if(currPath == ''){  // if at domain root, show the ad.
    $('.sidebar').show();
  }else {
    $('.sidebar').hide();
  }
  
  // Just for the demo.
  $("#test").on("click",function(){
    $('.sidebar').show();
  });

});
.sidebar{
  position:fixed;
  top:0;
  right:0;
  width:6em;
  height:100vh;
  background-color:green;
  border-left:2px dotted yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="domain"></div>
<div class="path"></div>
<div class="sidebar">Buy my products now!</div>
<button id="test">Show the ad</button>

如果您不需要访问域,则可以通过仅使用pathname来简化此操作……但是在这种情况下,您必须测试'/'而不是空值:< / p>

$(function(){

  var currPath = window.location.pathname; 
  console.log(currPath);  
  
  $('.path').text('Current path is : '+ currPath);
  
  if(currPath == '/'){  // if at domain root, show the ad.
    $('.sidebar').show();
  }else {
    $('.sidebar').hide();
  }
  
  // Just for the demo.
  $("#test").on("click",function(){
    $('.sidebar').show();
  });

});
.sidebar{
  position:fixed;
  top:0;
  right:0;
  width:6em;
  height:100vh;
  background-color:green;
  border-left:2px dotted yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="path"></div>
<div class="sidebar">Buy my products now!</div>
<button id="test">Show the ad</button>

在上述SO摘录中,页面pathname/js ...
;)

相关问题