繁体   English   中英

URL包含特定文本部分时显示或隐藏div

[英]Show or hide div when URL contains certain section of text

我有以下代码:

    <script>
if (/en/.test(window.location.href)) {
  document.getElementById('slogannederlands').style.display = 'none';
}

    if (/nl/.test(window.location.href)) {
  document.getElementById('sloganenglish').style.display = 'none';
}

</script>

根据URL是否以/ en /或/ nl / 结尾 ,它不会显示特定的div。 也可以这样做,如果它在URL中显示/ en /或/ nl / ANYWHERE ,它将执行相同的操作?

谢谢,埃迪

您可以使用split来创建一个数组,如果数组长度大于1,则搜索字符串存在。

var url = window.location.href
if(url.split('/en/').length > 1) {
   //success
}

jsfiddle示例

您可以使用indexOf:

var url = window.location.href;

if (url.indexOf("/en/") > -1)
{
    document.getElementById('slogannederlands').style.display = 'none';
    document.getElementById('sloganenglish').style.display = 'true';
}

else if (url.indexOf("/nl/") > -1)
{
    document.getElementById('sloganenglish').style.display = 'none';
    document.getElementById('slogannederlands').style.display = 'true';
}

indexOf返回该字符串在另一个字符串中的位置。 如果找不到,它将返回-1

因此,在/en//nl/中的哪个位置都没有关系。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM