Drop down container in JavaScript
I need to show and hide a div
in JavaScript. I'm using a more a
link. When a user clicks on the link the drop down the container will be shown and when a开发者_如何学JAVA user click on the same more link the div
should be hidden again. Initially the div
has its display set to none.
JavaScript:
function show(get){
if(document.getElementById(get).style.display="none")
{
document.getElementById(get).style.display="";
}
else{
document.getElementById(get).style.display="none";
}
}
HTML:
<div id="moreOffice">
<a href="#" onclick="show('showOffice');">More</a>
<div id="showOffice" style="display:none;">
hai the drop box is here.
</div></div>
The problem is when I click on the more link the function triggers show()
and the div
is showing, but when I click on more again the div
is not hiding.
you have missing the == operator you are using =. it must be like this .......
function show(get){
if(document.getElementById(get).style.display=="none")
{
document.getElementById(get).style.display="";
}
else{
document.getElementById(get).style.display="none";
}
}
You are assigning 'display' to 'none' everytime the if statement executes and evalutating to 'true' and then setting 'display' equal to ''. Just a syntax error in your js.
if(document.getElementById(get).style.display="none")
Use this instead:
function show(get){
if(document.getElementById(get).style.display == "none")
{
document.getElementById(get).style.display = "";
}
else{
document.getElementById(get).style.display = "none";
}
}
use jquery toggle function to hide and show the div
http://api.jquery.com/toggle-event/
<script>
$(document).ready(function(){
$("#more").click(function(){
$("#showOffice").toggle();
});
});
</script>
<div id="moreOffice">
<a href="#" id="more"">More</a>
<div id="showOffice" style="display:none;">
hai the drop box is here.
</div></div>
if you can use jQuery then do so because all you then need to do is the following;
$(".DIVNAME").toggle();
or on a click of an element;\
$(".CLICKEDELEMENT").click(function(){
$(".DIVNAME").toggle();
});
Try
JavaScript
function show(get) {
if (!document.getElementById) {
return false;
}
var divID = document.getElementById(get);
if (divID) {
if (divID.style.display == "none") {
divID.style.display = "inline";
divID.style.visibility = "visible";
} else if (divID.style.display == "" || divID.style.display == "inline") {
divID.style.display = "none";
divID.style.visibility = "hidden";
}
} else {
return false;
}
}
HTML
<div id="moreOffice">
<a href="#" onclick="show('showOffice'); return false">More</a>
<div id="showOffice" style="display:none;">
hai the drop box is here.
</div>
</div>
精彩评论