javascript 如果 URL 包含单词,则隐藏 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11436586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hide div if URL contains word
提问by Ashton Williams
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:
如果页面的 url 包含某个单词,我需要隐藏一个 div。感谢这个网站,我能够成功地找到 url 是否包含这个词。此代码有效:
<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
任何人都知道这段代码有什么问题吗?非常感谢任何帮助谢谢
回答by Joe
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"
等待整个文档“就绪”
回答by Dylan Douglas
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 尚未加载。
回答by Grokodile
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.
您正在构建 HTML 时运行内联脚本,在脚本运行时没有div
命名#notBarEnds
,您需要在文档加载后将其作为函数运行。
回答by ZiTAL
i write it without checking it, if doesn't work change de regex :D
我写它没有检查它,如果不起作用更改正则表达式:D
$(document).on('ready', function()
{
if(window.location.href.match(/Bar\-Ends/i))
$("#notBarEnds").hide();
});