簡體   English   中英

jQuery在首頁中隱藏/顯示div

[英]jQuery hide/show div in home page

我有一個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 {}

})

pathname屬性不包含域,因此您必須將其測試為/ (根)...

在下面,我使用了full 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來簡化此操作……但是在這種情況下,您必須測試'/'而不是空值:

 $(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 ...
;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM