隐藏基于url的div但是在Head中使用JS

时间:2014-09-05 00:01:15

标签: javascript

我有这个:

<div id="myelement"><p>I want hide this text if current URL contain s0dagvLc</p></div>

和此:

if (window.location.href.indexOf('s0dagvLc') != -1) {
document.getElementById('myelement').style.display='none';

}

并且代码工作Onload但不在Head内部。我测试了一堆没有更多运气的代码。我不明白其中的区别。这里有一个小提琴:http://jsfiddle.net/s0dagvLc/14/

2 个答案:

答案 0 :(得分:2)

使用DOMContentLoaded的事件监听器包装它。

document.addEventListener('DOMContentLoaded', function(){
  if (window.location.href.indexOf('s0dagvLc') != -1) {
    document.getElementById('myelement').style.display='none';
  }
});

答案 1 :(得分:0)

你可以试试这个

<body onload="display()">
  <div id="demo"  ><p>I want hide this text if current URL contain s0dagvLc</p></div>
</body>

<script>
function display(){
    if( /fiddle/.test(window.location.host) ){
       document.getElementById("demo").style.display = 'none';
    }
}
</script>