簡體   English   中英

有條件地隱藏所有帖子上的div但不包括​​類別頁面

[英]Conditionally hide div on all posts but not category page

如何在除WordPress類別頁面上的帖子之外的所有帖子上隱藏div?

我目前有以下jQuery但無法讓它工作 -

jQuery(function(){
      if (window.location.pathname == "offonalim.com/category/fashion.html"||window.location.pathname == "offonalim.com/category/interior.html"||window.location.pathname == "offonalim.com/category/travel.html"||window.location.pathname == "offonalim.com/category/work.html") {
            jQuery('.qodef-post-title').show();
            jQuery('.qodef-post-info').show();
      } else {
            jQuery('.qodef-post-title').hide();
            jQuery('.qodef-post-info').hide();
      }
 });

我可以看到您網站的類別頁面在每個網址中都包含關鍵字"Category" ,因此您可以使用此關鍵字檢查網址是否包含此特定關鍵字,然后相應地顯示或隱藏div

無需指定完整的URL。

<script type="text/javascript">
function myFunction(){
   val path=window.location.pathname;
      if(window.location.href.indexOf("category") > -1) {
            $('.qodef-post-title').show();
            $('.qodef-post-info').show();
      } else {
            $('.qodef-post-title').hide();
        $('.qodef-post-info').hide();
      }
 }
 myFunction();
 </script>

window.location.pathname產生路徑名,而不是整個URL。 因此,您的代碼在邏輯上是不正確的。

而不是單獨檢查每個路徑,理想的做法是創建一個可能的路徑數組並檢查該數組中的位置路徑。 像這樣的東西應該工作正常:

var catPaths = [
  "/category/fashion.html",
  "/category/interior.html",
  "/category/travel.html",
  "/category/work.html"
];

jQuery(function() {
  if (catPaths.includes(window.location.pathname)) {
    jQuery('.qodef-post-title').show();
    jQuery('.qodef-post-info').show();
  } else {
    jQuery('.qodef-post-title').hide();
    jQuery('.qodef-post-info').hide();
  }
});

您可以通過使用toggle()和分組選擇器來進一步最小化代碼:

jQuery(function() {
  var includes = catPaths.includes(window.location.pathname);
  jQuery('.qodef-post-title, .qodef-post-info').toggle(includes);
});

暫無
暫無

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

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