Javascript中基于URL匹配的显示/隐藏元素

问题描述 投票:0回答:1

这里是新手,首先尝试让脚本用于 a/b 测试。 我有一个元素“prodBanEle”,仅当页面上存在的另一个元素中最多三个其他 URL(topBanUrl1、topBanUrl2、topBanUrl3)是当前 URL 的一部分时,我才希望看到该元素。

例如:如果您访问“mywebsite.com/category-grey-pants/product-light-grey-shorts/”,则仅当“mywebsite.com/category-grey-pants/”为三个 URL 之一。

如果当前 URL 为“mywebsite.com/category-shorts/product-light-grey-shorts/”,则“prodBanEle”不应可见。

这就是我试图实现的工作,我最不确定的是indexOf实际上适用于变量,或仅适用于字符串。但我确信其中还有很多其他错误......

$(function(){
    var prodBanEle = document.getElementById("addToCardButtonDiv").getElementsByClassName("banner ")[0];
    var topBanUrl1 = document.getElementById("top_banner_url_1");
    var topBanUrl2 = document.getElementById("top_banner_url_2");
    var topBanUrl3 = document.getElementById("top_banner_url_3");
        if (window.location.href.indexOf(topBanUrl1)){
                prodBanEle.style.display = "block";
        } 
        else if (window.location.href.indexOf(topBanUrl2)){
                prodBanEle.style.display = "block";
        }
        else if (window.location.href.indexOf(topBanUrl3)){
                prodBanEle.style.display = "block";
        }
        else { prodBanEle.style.display = "none";
        }
    }
  );

是否有任何明显的错误您可以立即识别,或者它应该起作用吗?

谢谢您的帮助!

javascript
1个回答
0
投票
  1. 不要那样混合 jQuery 和 DOM
  2. 缓存该值,不再继续请求它
  3. 我假设 document.getElementById("top_banner_url_1") 是带有 href 的链接?

如果我看到一些 HTML,我可以更好地回答

document.addEventListener('DOMContentLoaded', () => {
  let prodBanEle = document.getElementById("addToCardButtonDiv").querySelector(".banner");
  let topBanIDs = ["top_banner_url_1", "top_banner_url_2", "top_banner_url_3"];
  let href = window.location.href;
  prodBanEle.hidden = !topBanIDs.some(id => href.includes(document.getElementById(id).href)); // assuming a link
});
© www.soinside.com 2019 - 2024. All rights reserved.