how to show/hide multiple divs based on input valu

2019-09-03 08:41发布

问题:

i created a fake console navigation for my site where people would have to enter a specific value or 'command' to show the div that it corresponds to. i got this to work for one div but i'm wondering how i can get it to work with multiple divs. when i tried this jquery script the divs show up fine independently, but if i try searching for one after the other, #div2 shows up on the left of #div1 and does some weird flickering, or #div1 refuses to disappear.

  
  var div = $('#div1').hide();

$('input').keydown(function() {

   var value = this.value;

   if ($('input').val() == 'div1') {
       $('#div1').slideDown();
   } else {
      div.hide();
   }

});

  
  var div = $('#div2').hide();

$('input').keydown(function() {

   var value = this.value;

  if ($('input').val() == 'div2') {
       $('#div2').slideDown();
  } else {
      div.hide(); 
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>


<input type="text" placeholder="ENTER 'div1' or 'div2' COMMAND" />

<div id="div1">div1 content</div>
<div id="div2">div2 content</div>

i want the divs to disappear when you backspace and enter in the input entry field, and i want the current div to disappear when you enter a new command. so what do i need to change? do the divs need to go in wrapper?

回答1:

Try this snippet!

// Hide both <div> by default
$('#div1').hide();
$('#div2').hide();

// Check on keydown
$('input').keydown(function() {
  if ($('input').val() == 'div1') {  // If input value is div1
       $('#div2').hide();
       $('#div1').slideDown();
  } else if ($('input').val() == 'div2') {  // If input value is div2
       $('#div1').hide();
       $('#div2').slideDown();
  } else {  // If input value is not equal to div1 or div2, hide both
      $('#div1').hide();
      $('#div2').hide();
  }
});

You can also have a common CSS class like .hide with display: none; property to initially hide the <div>.

Hope it helps!



回答2:

Try to add one common Class for all div and show/hide using the name of class

search for all this class divs and hide them

for exmaple

HTML

<div id="div1" class="CommonClass">div1 content</div>
<div id="div2" class="CommonClass">div2 content</div>

JS

$(".CommonClass").each(function(index,obj)){
    $(obj).hide(); // Or $(obj).css("display","none")
}


回答3:

Ok you can simplify it by and use .keyup() instead of .keydown()

$('div[id^=div]').hide();
$('input').keyup(function() {
   var id = $.trim($(this).val().toLowerCase());
   $('div[id^=div]').hide();
   $('#'+id).slideDown();
});

DEMO