当前位置: 动力学知识库 > 问答 > 编程问答 >

html - style.visibility='hidden' in JavaScript is not working

问题描述:

I have a Javascript code that handles onchange and onfocus event on my combo box. So that it shows only the one that is being selected by the user on the combo box.

I have this Javascript code:

var prev = "";

function pagechange(topage) {

frompage = prev;

var page=document.getElementById('formpage_'+frompage);

if (!page) return false;

page.style.display='none';

page.style.visibility='hidden';

page=document.getElementById('formpage_'+topage);

if (!page) return false;

page.style.display='block';

page.style.visibility='visible';

return true;

}

function set(){

var e = document.getElementById("usertype");

var selection = e.options[e.selectedIndex].text;

pagechange(selection);

}

function getPrevious(){

var e = document.getElementById("usertype");

var selection = e.options[e.selectedIndex].text;

prev = selection;

}

And this one is for my combo box:

 <select id="usertype" name="usertype" class="dropdown-select" autofocus="autofocus" onchange="set()" onfocus="getPrevious()" >

<option value="1" selected="selected">Chairperson</option>

<option value="2">Dean</option>

<option value="3">Faculty</option>

<option value="4">Staff</option>

<option value="5">Student</option>

<option value="6">Admin</option>

</select>

I've tried it. Yes, it shows what the user has selected but it does not hide the previous one.

What do you think is wrong in my code? or what must be modified?

网友答案:

You have too much faith in the onfocus event. Unlike what you expect, it's not always triggered before new selection is made. For example (at least in Chrome) if you just click the arrow and change selection, it won't be triggered. Hence, you don't have the previous selection to hide.

Just get rid of the getPrevious() method and instead store the previous after showing selected:

function pagechange(topage) {
    var page;
    if (prev.length > 0) {
        page = document.getElementById('formpage_' + prev);
        if (page)
            page.style.display = 'none';
    }

    page = document.getElementById('formpage_' + topage);
    if (!page)
        return false;

    page.style.display = 'block';
    prev = topage;
    return true;
}

Live test case.

If you insist on changing visibility as well be my guest, but it won't make any difference thus removed in my example. (if you can prove otherwise I'll be glad to stand corrected)

分享给朋友:
您可能感兴趣的文章:
随机阅读: