开发者

JS variable issue

I have a very simple js function to toggle div visibility, here's the working version:

function Toggle(obj) {   
    var state = document.getElementById(obj);
    if (state.style.display === 'block') {
        state.style.display = 'none';
    }
    else {
        state.style.display = 'block';
    }
}

Here obj represents the id of a div. Now, I have multiple divs on page, and want when user opens a new div, to have previously opened div closed. I tried to do it by modifying my function like this:

var prev_obj = 'empty';

 function Toggle(obj) {  
    var state = document.getElementById(obj);
    if (state.style.display === 'block') {
        state.style.display = 'none';
    }
    else {

                if (prev_obj !== 'empty')
                {
        var prev_state = document.getElementById(prev_obj)
        prev_state.style.display = 'none';
                }       
        state.style.display = 'block';

                prev_obj = obj;
    }
}

I g开发者_JAVA技巧uess this is self explanatory to js wizards out there, so I'll just say, when I hard-code the value for prev_obj, it works, but when I don't it doesn't, and firebug shows that it's keeping the initial value ("empty")

Help appreciated as well as any other way to do this if you have it.


As I wrote in the comments, I suspect that the function is being called incorrectly as it looks like it should work.

On another note, you can simplify the logic a little, if you consider that what you want is the same as saying: "close the previous div no matter what (including if it's the same as the current div), and only open the current div if it is different to the previous one".

I'd also store the actual element in prev_obj instead of the ID, and set it to null initially. It'll make testing if there was a prev_obj easier, and also allows you to use the ID of "empty" if necessary (of course you probably won't, but just best practice).

var prev_obj = null;

function Toggle(id) { // Call it "id" to be clear it's not the actual object
   // Hide previous object if it exists
   if (prev_obj) prev_obj.style.display = 'none';

   // Show current object if it's the same as the previous one
   var obj = document.getElementById(id);
   if (obj !== prev_obj) {
      obj.style.display = 'block';
      prev_obj = obj;
   }
}

Make sure you call it by including single quotes around the id:

<div onclick="Toggle('div-id-here')"></div>


It is difficult to tell where your problem is from the details provided. You should be able to develop a solution with the tutorial linked below. Personally I'd loop over all the divs, hide them all, and then show the current one instead of holding a reference to the last div.

http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜