jquery隐藏问题

I use this to toggle my div elements, and hide all them when the DOM is ready...

   $('div[class*="showhide"]').hide();

   $('input:image').click( function() {
      var nr = $(this).attr('id').substr(7,2);
      $('div.showhide' + nr).toggle(400);
   });  

I have dynamically created div elements with class showhide0;showhide1;showhide2...etc... Inside the DIV tags I have search boxes.

  • First when page is loaded all DIV tags hide.
  • I toggle one of them to show.
  • Start a search, so the page is reloaded with the result of the query.

Of course all DIV is hide again, because the page is reloaded. Unfortunately...

Is it possible to not hide again after I searched for something? It would be nice when I open the page, all the divs are hidden, but after then just when I toggle it...

Well, yeah, you just don't run the initial hide() if there's a search request. I'd just exclude that line from the output if, on the PHP level, you know you're executing a search.

If you need a specific element or elements to stay visible upon a page reload, then you're going to need to do something to maintain state across requests, and then modify your jQuery to utilize that state information when initializing the visible state of the elements.

This can be done in numerous ways which include but are not necessarily limited to

  • Include it in the query string
  • Include it in the URL hash
  • Use a cookie

We do something similar to this where I work.

We opted instead of have the class name just be hide for all elements and instead have the ids named.

So, we'd have it something like:

<div id="hide1" class="hide"> </div>

along with this CSS to hide all those divs by default

.hide {
    display: none;
}

Finally, we use something like this to show them:

$('input:image').click( function() {
   var nr = $(this).attr('id').substr(7,2);
      $('#hide' + nr).toggle(400);
   });
}

This works because of CSS precedence rules. The toggle()/hide()/show() method overrides the hide class's style.

As for the unhiding part, if you pass the ID to unhide to your script, you can parse it and unhide the appropriate div.

You can read and process the query string from window.location.search. Unfortunately, you then have to manually parse it or use a plugin, such as jQuery Query String Object or jQuery URL Utils.

var id = $.query.get('unhide_id'); // This is using Query String Object
$('#' + id).show(400);