简体   繁体   中英

Using .hide() and .show() in jQuery

In my program I have several very similar drop-down menus all with the same name (foo in the following example). On change they hide or show a nearby div tag depending on whether or not "ON" was selected.

$('.togClass').hide();
        $('[name*="foo"]').change(function(){
            if ($('[value="ON"]').is(':selected')) {
                $('.togClass').show('blind', 1000);
            } else {
                $('.togClass').hide(1000);
            } 
        });

As it is, all of the div tags with class "togClass" toggle when any of the drop down menus choose "ON", is there a way that I can choose to show/hide only the nearby div to the drop-down that chooses "ON"(they are nested in the same div)? I don't want to write a copy of this function for every div I want to hide.

Here is how it works in the HTML:

<select name="foo">
    <option value="OFF">OFF</option>
    <option value="ON">ON</option>
</select><br/>
<div class="togClass">
    //Stuff
</div>

Ofcourse you can. Check out the jquery doc about traversing: http://api.jquery.com/category/traversing/ It has a lot of great examples.

For your problem the solution could be: .closest()

$('div.togClass').hide();
$('select[name*="foo"]').change(function(){
  if ($(this).val() == "ON") {
     $(this).siblings('div.togClass').show('blind', 1000);
  } else {
      $(this).siblings('div.togClass').hide(1000);
  } 
});

You have to tell us a bit more about what "nearby" means. But it appears that the fundamental piece you're missing is the use of $(this) within the change function. Instead of identifying any .togClass item, you want to identify a specific one relative to $(this) -- the element being changed.

Here's one way to do it with the assumption that the associated .togClass div is the next one to be found in the DOM.

$('[name*="foo"]').change(function(){
  if( $(this).is(':selected') ) { // relative to the selected item
    $(this).next('.togClass').show('blind',1000);
  } else {
    $(this).next('.togClass').hide(1000);
  }
});

Where you see .next() you'll actually need the appropriate jQuery traversal methods -- unlikely to be the one I've randomly assumed in the example.

How about using .closest() ?

Should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM