2012-11-05 32 views
0

我是一个完整的初学者,当谈到javascript,我试图创建一个简单的if/else语句来显示不同的div。使用Javascript if语句来显示或隐藏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

任何帮助将greatfully收到

+0

为了这个目的,使用JQuery会更好。 –

+1

你为什么只用JQuery来使用它? –

+2

'yes'和'no'应该是字符串而不是变量。 – l4mpi

回答

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> 

而且,埃文发现,你正在使用noyes而不是字符串'no''yes'

+0

这完成了这项工作非常谢谢!只要它让我接受这个答案 – tatty27

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'; 
} 
+0

但是,谢谢你的回答,因为Guffa指出它确实需要使用加载事件 – tatty27