2012-07-11 72 views
4

如果页面的url包含某个单词,我需要隐藏div。感谢这个网站,我已经能够成功地找到url是否包含这个词。此代码的工作:如果URL包含单词,请隐藏div

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

但由于某种原因,它不会工作隐藏一个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> 

任何人有任何的想法有什么不对这个代码? 任何帮助是极大的赞赏 感谢

+1

推迟该段的执行,因为该元素不存在(还)当脚本进行评估。 – 2012-07-11 15:55:03

+0

根据您提供的内容,您不会在DOM准备好时调用此代码,因此元素'$('#notBarEnds')'未准备好,您无法针对它调用事件。把它包装在'$(function(){// code})' – Ohgodwhy 2012-07-11 15:55:44

+1

我想你也可以在js上放一个$(document).ready(),它会工作 – 2012-07-11 15:56:45

回答

10

通知重新排序:

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

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

或者

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

等待整个文件是 “准备”

+0

谢谢乔,那个工​​作很完美! – 2012-07-11 16:11:58

2

尝试:

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

当脚本运行时,您的div未必尚未加载。

0

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

0

我把它写不检查它,如果还是不行的变化德正则表达式:d

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