Hide div if URL contains word

拜拜、爱过 提交于 2019-12-12 10:48:30

问题


I need to hide a div if the url of the page contains a certain word. 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:

<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


回答1:


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"




回答2:


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.




回答3:


You're running an inline script as the HTML is being constructed, there isn't a div named #notBarEnds at the time that the script runs, you need to run it as a function after the document has loaded.




回答4:


i write it without checking it, if doesn't work change de regex :D

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


来源:https://stackoverflow.com/questions/11436586/hide-div-if-url-contains-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!