使用Javascript if语句来显示或隐藏div

时间:2012-11-05 00:55:33

标签: javascript

当谈到javascript时,我是一个完全的初学者,我正在尝试创建一个简单的if / else语句,它将显示不同的div。

<script>
   if (window.FileReader && Modernizr.draganddrop){
      alert("Your browser supports drag and drop!!");
      document.getElementById(no).style.display = 'none';
   }else{
      alert("Sorry, browser does not support drag and drop!");
      document.getElementById(yes).style.display = 'none';
   }
</script>

然后,在身体

<div id="yes">Drag and drop yes</div>

<div id="no">Drag and drop no</div>

尽管modernizr工作得很好,但脚本显示两个div

任何帮助都会得到很好的接受

2 个答案:

答案 0 :(得分:4)

问题是getElementById需要一个字符串,据我所知你还没有声明是/否。

if (window.FileReader && Modernizr.draganddrop) {
    alert("Your browser supports drag and drop!!");
    document.getElementById('no').style.display = 'none';
} else {
    alert("Sorry, browser does not support drag and drop!");
    document.getElementById('yes').style.display = 'none';
}

答案 1 :(得分:0)

脚本在元素存在之前运行。使用load事件,以便在页面完全加载后运行代码:

<script>
window.onload = function() {
   if (window.FileReader && Modernizr.draganddrop){
      alert("Your browser supports drag and drop!!");
      document.getElementById('no').style.display = 'none';
   }else{
      alert("Sorry, browser does not support drag and drop!");
      document.getElementById('yes').style.display = 'none';
   }
};
</script>

此外,正如Evan发现的那样,您使用的是noyes,而不是字符串'no''yes'