最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Making visible object hidden and hidden object visible - Stack Overflow

programmeradmin0浏览0评论

I have a javascript function that is supposed to make visible objects hidden and hidden objects visible. since I lack of basic javascript knowlegde, I came here to ask help from you :/ Can someone help me out with my code so that I can learn a little?

function DisplayMenu(obj) {
            if (obj.style.visibility == 'visible') {
                obj = document.getElementById(obj);
                obj.style.visibility = 'hidden';
            }
            else if (obj.style.visibility == 'hidden') {
                obj = document.getElementById(obj);
                obj.style.visibility = 'visible';
            }
        }

I have a javascript function that is supposed to make visible objects hidden and hidden objects visible. since I lack of basic javascript knowlegde, I came here to ask help from you :/ Can someone help me out with my code so that I can learn a little?

function DisplayMenu(obj) {
            if (obj.style.visibility == 'visible') {
                obj = document.getElementById(obj);
                obj.style.visibility = 'hidden';
            }
            else if (obj.style.visibility == 'hidden') {
                obj = document.getElementById(obj);
                obj.style.visibility = 'visible';
            }
        }
Share asked May 24, 2012 at 9:10 Cute BearCute Bear 3,29113 gold badges47 silver badges70 bronze badges 1
  • there is something wrong with if else part I guess :/ – Cute Bear Commented May 24, 2012 at 9:10
Add a ment  | 

2 Answers 2

Reset to default 7

You need to define what obj is before the if:

function DisplayMenu(obj) {
    var obj = document.getElementById(obj);
            if (obj.style.visibility == 'visible') {
                obj.style.visibility = 'hidden';
            }
            else {
                obj.style.visibility = 'visible';
            }
        }

EDIT: You could simplify it, you don't need the else if just use else

And even shorter version which checks for existance of obj_id before assignment, so in the case there is no obj_id in DOM it doesn't trigger exception:

function DisplayMenu(obj_id) {
  var obj = document.getElementById(obj_id);
  obj && obj.style.visibility = (obj.style.visibility == 'visible') ? 'hidden' : 'visible';
}
发布评论

评论列表(0)

  1. 暂无评论