I wanna open a div and close it with this function but it doesnt work whe开发者_运维技巧re is the wrong part i couldnt fix it, can anyone help me ?
function Element(id)
{
if(document.getElementById(id).style.display = 'block')
{
document.getElementById(id).style.display = 'block';
}
else
{
document.getElementById(id).style.display = 'none';
}
}
Your if
statement assigns the property instead of comparing it.
Change =
to ===
.
I would suggest you rewrite it with the ternary operator, its much more readable and maintainable:
var element = document.getElementById(id);
element.style.display = element.style.display === 'block' ? 'none' : 'block';
function Element(id) {
if( document.getElementById(id).style.display == 'block') {
document.getElementById(id).style.display = 'block';
} else { document.getElementById(id).style.display = 'none'; }
}
Thank you ! This one worked.! but I changed the code inside of if. Because it says if you find block which should be none.
function Element(id) {
if( document.getElementById(id).style.display == 'none') {
document.getElementById(id).style.display = 'block';
} else {
document.getElementById(id).style.display = 'none';
}
}
You don't need an else
or a ternary operator as your first condition has no effect. So this will suffice...
if(document.getElementById(id).style.display != 'block')
{
document.getElementById(id).style.display = 'none';
};
精彩评论