简体   繁体   English

如果URL包含单词,则隐藏div

[英]Hide div if URL contains word

I need to hide a div if the url of the page contains a certain word. 如果页面的网址包含某个单词,我需要隐藏div。 Thanks to this site I have been able to successfully find if the url contains the word. 感谢这个网站,我已经能够成功找到该网址是否包含该字词。 This code works: 此代码有效:

<script type="text/javascript">
if (window.location.href.indexOf("Bar-Ends") != -1) {
alert("your url contains bar ends");
}
</script>

but for some reason it will not work to hide a div, like this: 但由于某种原因,隐藏div是行不通的,如下所示:

<script type="text/javascript">
if (window.location.href.indexOf("Bar-Ends") != -1) {
$("#notBarEnds").hide();
}
</script>

<div id="notBarEnds">this is not bar ends</div>

Anyone have any idea what is wrong with this code? 任何人都知道这段代码有什么问题吗? Any help is greatly appreciated Thanks 非常感谢任何帮助谢谢

Notice the reorder: 请注意重新排序:

<div id="notBarEnds">this is not bar ends</div>

<script type="text/javascript">
if (window.location.href.indexOf("Bar-Ends") != -1) {
$("#notBarEnds").hide();
}
</script>

Or 要么

<script type="text/javascript">
$(document).ready(function () {
    if (window.location.href.indexOf("Bar-Ends") != -1) {
        $("#notBarEnds").hide();
    }
}
</script>

Waiting for the entire document to be "ready" 等待整个文档“准备好”

Try: 尝试:

$(document).ready(function () {
  if (window.location.href.indexOf("Bar-Ends") != -1) {
    $("#notBarEnds").hide();
  }
});

Your div hasn't necessarily loaded yet when the script runs. 脚本运行时,您的div尚未加载。

您正在构建HTML时运行内联脚本,在脚本运行时没有名为#notBarEndsdiv ,您需要在文档加载后将其作为函数运行。

i write it without checking it, if doesn't work change de regex :D 我写它没有检查它,如果不起作用改变de regex:D

$(document).on('ready', function()
{
    if(window.location.href.match(/Bar\-Ends/i))
        $("#notBarEnds").hide();
});

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

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