单击父div时jQuery隐藏隐藏弹出窗口

时间:2018-12-29 16:52:45

标签: jquery html

我有<div>元素,其中有一个<span>元素用于课程设置。

当用户单击<div>元素时,应该打开相应的子<span>元素。

然后,理想情况下,当用户单击下一个<div>元素时,它将关闭上一个子<span>元素。

我什至无法打开第一个子元素<span>

下面是我的代码段:

$(document).ready(function() {
  var counter = 0;

  $(".popup").click(function() {
    $(this).closest('div').find('span').toggle("show");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="popup"> English: Human Nature
  <span class="popuptext" id="English9">
        <h1>Human Nature</h1>
			  <br>
	      9th Grade ELA Course Description
	  </span>
</div>
<div class="popup">English: Welcome to NY
  <span class="popuptext" id="EnglishELL">
        <h1>Welcome to NY</h1>
		    <br>
		    9th Grade ELA Course Description for ELLS
	 	</span>
</div>

我在做什么错,我该如何解决?

3 个答案:

答案 0 :(得分:1)

尝试以下代码

$(document).ready(function(){	
    var counter = 0;
   	
    $(".popup").click(function() {
        $(this).toggleClass('active');
        $(this).siblings('.popup').removeClass('active');
    });
});
.popuptext {
  display: none;
}
.popup.active > .popuptext {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="popup"> English: Human Nature
    <span class="popuptext" id="English9">
        <h1>Human Nature</h1>
	      <br>
	      9th Grade ELA Course Description
	  </span>
</div>	
<div class="popup">English: Welcome to NY
    <span class="popuptext" id="EnglishELL">
        <h1>Welcome to NY</h1>
		    <br>
	      9th Grade ELA Course Description for ELLS
	  </span>
</div>

答案 1 :(得分:0)

here my solution

$(document).ready(function(){   
  $(".popup").click(function() {
    if($(this).find('span').hasClass('active')) {//This can be save in 2 variables {
      $(this).find('span').removeClass('active');
    } else {
        $(this).parent().find('span').removeClass("active");
        $(this).find('span').toggleClass( "active" );
    }
  });
}); 

更新:无循环:)

$(document).ready(function(){   
  var active;
  $(".parent").click(function(e) {
    var target = $(e.target);
    if(!target) return;
    if($(active).hasClass('active')) {
      if(!$(target).find('span').hasClass('active')) {
        active.removeClass('active');
        active = $(target).find('span').addClass('active');
      } else {
          active = $(target).find('span').toggleClass('active')
      }
    } else {
        active = $(target).find('span').addClass('active');
    }
  });
}); 

答案 2 :(得分:0)

尝试一下

$(document).ready(function(){ 
      var spans = $('.popup span').hide();
      $(".popup").click(function() {
        var this_span = $(this).find('span'),
        is_visible = this_span.is(":visible");
        spans.hide();
        if (!is_visible) {
            this_span.show();
        }
        });
    });