【问题标题】:jQuery click event not working to close modal windowjQuery单击事件无法关闭模式窗口
【发布时间】:2021-10-21 15:17:25
【问题描述】:

我用 jQuery 制作了一个灯箱,如果我选择使用 body 标记作为单击并关闭的目标,则可以关闭模​​式窗口。但是,如果我将其更改为我的 .closeBtn,则不会发生任何事情。我已经尝试了几种我所知道的让它工作的变体,但没有运气。任何信息将不胜感激。

干杯

// USING JQUERY CDN

$( document ).ready(function() {
       $('.lightbox-trigger').click(function(e) {
        e.preventDefault();
        let image_href = $(this).attr("href");
        if ($('#lightbox').length > 0) { 
            $('#content').html('<img src="' + image_href + '" />');
            $('#lightbox').show('fast');
        } else { 
            let lightbox = 
            '<div id="lightbox">' +
                '<p class="closeBtn">&times;</p>' +
                '<div id="content">' + 
              '<img class="lightbox-img" src="' + image_href +'" />' +
                '</div>' +  
                '<a class="prev arrowBTN" aria-label="previous page">&#10094;</a>' + 
                '<a class="next arrowBTN" aria-label="next page">&#10095;</a>' +
            '</div>';
            $('body').append(lightbox);
        }
         $('.gallery-container').addClass('lightbox-active');
    });
     
    $('.closeBtn').on('click', '#lightbox', function() { 
        $('#lightbox').hide();
      $('.gallery-container').removeClass('lightbox-active');
    });
});
// END OF FUNCTION
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-color: black;
}

body {
  color: white;
  font-family: 'Montserrat';
}

/* ///////////////////// NAVBAR //////////////////////// */
.navbar-style {
  box-shadow: 0 4px 2px -2px #333;
}

.nav-logo {
  width: 10%;
}

.nav-custom img {
  width: 64px;
}

.icon-bar {
  background: white;
}

/* ///////////////////// NAVBAR //////////////////////// */

/* ///////////////////// MAIN AREA //////////////////////// */

.slogan h1 {
  font-weight: 200;
  font-size: 1.2rem;
  margin-top: 2rem;
  margin-left: 2rem;
}

.background-img img {
  width: 80%;
}

.button {
  margin-top: 2rem;
  margin-left: 2rem;
  background-color: black;
}

.blurb {
  font-family: 'League Script', cursive;
  font-weight: 100;
  margin-top: 2rem;
  margin-left: 2rem;
}

/* ///////////////////// FRONT GALLERY //////////////////////// */



.gallery-container {
  display: flex;
  justify-content: center;
  border: solid 1px white;
  margin: 0, auto;
}

.flex-column {
  justify-content: space-between; /* have images appear as a four sided block */
  max-width: 250px;
}

/* ---------- LIGHTBOX ---------- */

#lightbox {
  position: fixed; 
/*  ^keeps lightbox window in the current viewport  */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  background: rgba(0,0,0,.7);
  
}

/* LIGHTBOX CLOSE BUTTON */
#lightbox .closeBtn {
  text-align: right;
  margin-right: 20px;
  font-size: 3rem;
}

.closeBtn {
  cursor: pointer;
}

/* LIGHTBOX IMAGE */
#lightbox img {
  box-shadow: 0 0 25px #111;
  max-width: 300px;
}

#content {
  display: flex;
  justify-content: center;
}

#content img{
  position: fixed;
  top: 0;
  margin-top: 4rem;
  width: 100%;
}

/* BLUR BACKGROUND WHEN LIGHTBOX IS ACTIVE */
.lightbox-active {
  filter: blur(5px);
}


/* LIGHTBOX ARROWS */
.arrowBTN {
  position: absolute;
  text-decoration: none;
  color: white;
  font-size: 2rem;
  text-align: center;
  margin-top: 25%;
  transform: translateY(-25%);
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  background-color: rgba(255,255,255,0.5);
}

.prev {
  left: 0;
  margin-left: 1rem;
}

.next {
  right: 0;
  margin-right: 1rem;
}

#lightbox a {
  text-decoration: none;
   color: white;
}

#lightbox a:hover {
   background-color: rgba(255,255,255, 0.2);
}




















@media screen and (min-width: 1650px) {
  .flex-column {
    display: flex;
    justify-content: space-evenly;
  }
}

img {
  margin: 5px;
}



/* ///////////////////////////////////// */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="front-gallery">
      <div class="container-fluid gallery-container">
        <div class="d-flex flex-row">
          
<!--   ////////  1st COLUMN   ////////    -->    
          <div class="d-flex flex-column">
<!--      FIRST IMAGE        -->
            <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/04/05/17/45/girl-2205813_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2017/04/05/17/45/girl-2205813_1280.jpg" alt="woman black and white photo" class="img-fluid">
            </a>
            
<!--      SECOND IMAGE        -->
            <a style="display:contents" href="https://cdn.pixabay.com/photo/2014/10/13/18/10/woman-487090_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2014/10/13/18/10/woman-487090_1280.jpg" alt="dog" class="img-fluid">
            </a>
          </div>
          
<!--   ////////  2nd COLUMN   ////////    -->       
    <div class="d-flex flex-column">
<!--      THIRD IMAGE        -->
       <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/29/13/00/black-1869685_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2016/11/29/13/00/black-1869685_1280.jpg" alt="woman color photo" class="img-fluid">
      </a>
<!--      FOURTH IMAGE        -->   
             <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/03/04/19/42/woman-659352_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2015/03/04/19/42/woman-659352_1280.jpg" alt="woman with tattoos" class="img-fluid">
      </a>
            </div>
          
 <!--   ////////  3rd COLUMN   ////////    -->     
  <div class="d-flex flex-column">
<!--      FIFTH IMAGE        -->  
                 <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/07/02/10/11/person-828630_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2015/07/02/10/11/person-828630_1280.jpg" alt="outline of man photo" class="img-fluid">
    </a>
    
<!--      SIXTH IMAGE        -->   
     <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/05/27/17/52/model-2349037_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2017/05/27/17/52/model-2349037_1280.jpg" alt="woman under water" class="img-fluid">
    </a>
            </div>
          
<!--   ////////  4th COLUMN   ////////    -->              
  <div class="d-flex flex-column">
 <!--      SEVENTH IMAGE        -->  
         <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/02/11/19/14/couple-1194312_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2016/02/11/19/14/couple-1194312_1280.jpg" alt="couple" class="img-fluid">
    </a>

<!--      EIGHTH IMAGE        -->  
             <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/11/03/10/34/studio-2913936_1280.jpg" class="lightbox-trigger">
            <img src="https://cdn.pixabay.com/photo/2017/11/03/10/34/studio-2913936_1280.jpg" alt="woman smiling" class="img-fluid">
               </a>
            </div>
          
 <!--   ////////  5th COLUMN   ////////    -->             
  <div class="d-flex flex-column">
<!--      NINTH IMAGE        -->    
             <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/14/04/08/selfie-1822563_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2016/11/14/04/08/selfie-1822563_1280.jpg" alt="kids taking selfie in field" class="img-fluid">
               </a>
    
<!--      TENTH IMAGE        -->  
                        <a style="display:contents" href="https://cdn.pixabay.com/photo/2021/04/02/12/01/woman-6144753_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2021/04/02/12/01/woman-6144753_1280.jpg" alt="woman with eye makeup" class="img-fluid">
                          </a>
            </div>
          
 <!--   ////////  6th COLUMN   ////////    -->             
  <div class="d-flex flex-column">
<!--      ELEVENTH IMAGE        -->   
             <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/10/27/03/43/radio-1773304_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2016/10/27/03/43/radio-1773304_1280.jpg" alt="vintage radio" class="img-fluid">
               </a>
    
<!--      TWELFTH IMAGE        -->    
                        <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/06/24/01/16/photographer-819365_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2015/06/24/01/16/photographer-819365_1280.jpg" alt="outdoor photographer" class="img-fluid">
                          </a>
            </div>
          
 <!--   ////////  7th COLUMN   ////////    -->             
  <div class="d-flex flex-column">
    
<!--      THITEENTH IMAGE        -->  
             <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/04/12/18/05/man-719228_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2015/04/12/18/05/man-719228_1280.jpg" alt="man thinking" class="img-fluid">
               </a>
    
<!--      FOURTEENTH IMAGE        -->   
                        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/29/01/34/man-1866572_1280.jpg" class="lightbox-trigger">
              <img src="https://cdn.pixabay.com/photo/2016/11/29/01/34/man-1866572_1280.jpg" alt="man with jacket" class="img-fluid">
                          </a>
            </div>
          
          
          </div> <!-- END FLEX ROW -->
      </div>  <!-- END CONTAINER -->
    </section>



<!-- ////////////////////////////// -->
<!-- <div id="lightbox2">
  <p class="closeBtn2">&times;</p>
  <div id="content2">
    <img class="lightbox-img2" src="' + image_href +'" />
    <img class="lightbox-img2" src="https://cdn.pixabay.com/photo/2016/11/14/04/08/selfie-1822563_1280.jpg" />
  </div>
 
  <a class="prev2 arrowBTN2" aria-label="previous page">&#10094;</a>
  <a class="next2 arrowBTN2" aria-label="next page">&#10095;</a>
</div> -->

【问题讨论】:

  • 这能回答你的问题吗? Event binding on dynamically created elements?
  • jQuery 事件仅适用于在添加事件时存在的元素。在$('.closeBtn').on('click' 行之前添加console.log($('.closeBtn').length) - 它可能为零,如果不是,它肯定不会引用您稍后添加的 .closeBtn。
  • 您对$('.closeBtn').on('click', '#lightbox', 的使用也不正确,因为呼叫是$("existing_selector").on("click", "selector_for_child_of_existing_selector" - 并且#lightbox 不是.closeBtn 的孩子 - 你可能想要@987654331 @ 以确保只有灯箱中的按钮被点击。
  • 附加一个新的&lt;div id="lightbox"&gt; 为什么不直接放置一个静态的,然后根据需要进行更改?
  • 如果你只显示一个静态 div 将正常工作(顺便说一句,在显示之前更新你的内容 - 经常看到这个:$(div).show().html(new_html) 它会弹出旧内容 - 糟糕UX - 甚至发生在 Chrome 工具提示中!)。否则,没有理由不使用事件委托。

标签: jquery click onclicklistener


【解决方案1】:

这不是完整的功能,因为您没有指定如何实现灯箱功能(插件?)但这不是问题,问题是如何实现点击 - 这里我展示了一个内部灯箱的静态 div #first-container 但是,如果您希望动态插入一个也可以这样做。

我还展示了如何添加第二个。我只是用所有附加的事件处理程序克隆了第一个并将其附加到第二个容器,然后触发了一个用数据属性指向的图像-这里的键是单击事件处理程序适用于关闭按钮,因为它附加到lightbox-container

$(function() {
  $('.lightbox-trigger').on('click', function(event) {
    event.preventDefault();
    let imageHref = $(this).attr("href");
    let targetBox = $(this).data('targetlightbox');
    //console.log("tb:",targetBox);
    //target or default selector set for targetBox
    targetBox = targetBox ? targetBox : '.lightbox-thing:first';
    console.log("tb:",targetBox);
    let lightBox = $(targetBox);
    lightBox.find('.lightbox-content').find('.lightbox-img').attr('src', imageHref);
    lightBox.show('fast');
    $('.gallery-container').addClass('lightbox-active');
  });
  $('.lightbox-container').on('click', '.closeBtn', function(event) {
    $(event.delegateTarget).find('.lightbox-thing').hide(); // the lightbox
    $('.gallery-container.lightbox-active').removeClass('lightbox-active');
  });

  /* add a second lightbox - by cloning first one */
  /* rather than embed in script, I just cloned the prior one here but it IS dynamic */
  let newBox = $('.lightbox-container:first').find('.lightbox-thing').clone(true);
  newBox.addClass('new-lightbox');
  // console.log("nb:",newBox.length);
  // console.log(newBox.attr('class'));
  $('#second-container').append(newBox);
  // console.log("appended:",$(".lightbox-thing").last().attr('class'), $('.lightbox-trigger').last().data('xx'));
  $('.lightbox-trigger').last().trigger('click');//trigger click on last which has a target
 // $('.lightbox-trigger').eq(2).trigger('click');
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-color: black;
}

body {
  color: white;
  font-family: 'Montserrat';
}

.icon-bar {
  background: white;
}

.slogan h1 {
  font-weight: 200;
  font-size: 1.2rem;
  margin-top: 2rem;
  margin-left: 2rem;
}

.background-img img {
  width: 80%;
}

.button {
  margin-top: 2rem;
  margin-left: 2rem;
  background-color: black;
}

.blurb {
  font-family: 'League Script', cursive;
  font-weight: 100;
  margin-top: 2rem;
  margin-left: 2rem;
}

.gallery-container {
  display: flex;
  justify-content: center;
  border: solid 1px white;
  margin: 0, auto;
}

.flex-column {
  justify-content: space-between;
  max-width: 250px;
}

.lightbox-container {
  position: fixed;
  /*  ^keeps lightbox window in the current viewport  */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  background: rgba(0, 0, 0, .7);
  border: solid yellow 1px;
}

.lightbox-container .closeBtn {
  text-align: right;
  margin-right: 20px;
  font-size: 3rem;
}

.closeBtn {
  cursor: pointer;
}

.lightbox-container img {
  box-shadow: 0 0 25px #111;
  max-width: 300px;
}

.lightbox-content {
  display: flex;
  justify-content: center;
}

.lightbox-container .lightbox-content img {
  position: fixed;
  top: 0;
  margin-top: 4rem;
  width: 100%;
}

.lightbox-active {
  filter: blur(5px);
}

.arrowBTN {
  position: absolute;
  text-decoration: none;
  color: white;
  font-size: 2rem;
  text-align: center;
  margin-top: 25%;
  transform: translateY(-25%);
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
}

.prev {
  left: 0;
  margin-left: 1rem;
}

.next {
  right: 0;
  margin-right: 1rem;
}

.lightbox-container a {
  text-decoration: none;
  color: white;
}

.lightbox-container a:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

@media screen and (min-width: 1650px) {
  .flex-column {
    display: flex;
    justify-content: space-evenly;
  }
}

img {
  margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<section id="front-gallery">
  <div class="container-fluid gallery-container">
    <div class="d-flex flex-row">
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/04/05/17/45/girl-2205813_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2017/04/05/17/45/girl-2205813_1280.jpg" alt="woman black and white photo" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2014/10/13/18/10/woman-487090_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2014/10/13/18/10/woman-487090_1280.jpg" alt="dog" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/29/13/00/black-1869685_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2016/11/29/13/00/black-1869685_1280.jpg" alt="woman color photo" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/03/04/19/42/woman-659352_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2015/03/04/19/42/woman-659352_1280.jpg" alt="woman with tattoos" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/07/02/10/11/person-828630_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2015/07/02/10/11/person-828630_1280.jpg" alt="outline of man photo" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/05/27/17/52/model-2349037_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2017/05/27/17/52/model-2349037_1280.jpg" alt="woman under water" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/02/11/19/14/couple-1194312_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2016/02/11/19/14/couple-1194312_1280.jpg" alt="couple" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2017/11/03/10/34/studio-2913936_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2017/11/03/10/34/studio-2913936_1280.jpg" alt="woman smiling" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/14/04/08/selfie-1822563_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2016/11/14/04/08/selfie-1822563_1280.jpg" alt="kids taking selfie in field" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2021/04/02/12/01/woman-6144753_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2021/04/02/12/01/woman-6144753_1280.jpg" alt="woman with eye makeup" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/10/27/03/43/radio-1773304_1280.jpg" class="lightbox-trigger" data-targetlightbox=".new-lightbox">
          <img src="https://cdn.pixabay.com/photo/2016/10/27/03/43/radio-1773304_1280.jpg" alt="vintage radio" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/06/24/01/16/photographer-819365_1280.jpg" class="lightbox-trigger">
          <img src="https://cdn.pixabay.com/photo/2015/06/24/01/16/photographer-819365_1280.jpg" alt="outdoor photographer" class="img-fluid">
        </a>
      </div>
      <div class="d-flex flex-column">
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2015/04/12/18/05/man-719228_1280.jpg" class="lightbox-trigger" data-targetlightbox=".new-lightbox">
          <img src="https://cdn.pixabay.com/photo/2015/04/12/18/05/man-719228_1280.jpg" alt="man thinking" class="img-fluid">
        </a>
        <a style="display:contents" href="https://cdn.pixabay.com/photo/2016/11/29/01/34/man-1866572_1280.jpg" class="lightbox-trigger" data-targetlightbox=".new-lightbox">
          <img src="https://cdn.pixabay.com/photo/2016/11/29/01/34/man-1866572_1280.jpg" alt="man with jacket" class="img-fluid">
        </a>
      </div>
    </div>
  </div>
</section>
<div id="first-container" class="lightbox-container">
  <div class="lightbox-thing">
    <p class="closeBtn">&times;</p>
    <div class="lightbox-content">
      <img class="lightbox-img" src="#" />
    </div>
    <a class="prev arrowBTN" aria-label="previous page">&#10094;</a>
    <a class="next arrowBTN" aria-label="next page">&#10095;</a>
  </div>
</div>
<div id="second-container" class="lightbox-container">
</div>

【讨论】:

  • 非常感谢您抽出宝贵时间帮助我解决这个问题!非常感谢您的努力。因此,我采纳了您的建议,将 Lightbox 设为静态。现在,我正试图找到一种方法来做一些事情。第一种:当用户点击图库中的图片时,点击的图片会在 Lightbox 中弹出。第二,一旦灯箱处于活动状态,用户就可以使用左右箭头依次导航到下一个/上一个图像。到目前为止没有任何运气。如果你想看看我有什么,我已经做了一个 Codepen。 codepen.io/kurt-reynolds/pen/yLoVmoy再次感谢您!!!
【解决方案2】:

这是因为,您正在尝试单击动态生成的按钮。 试试这个,

$('body').on('click', '#lightbox .closeBtn', function() { 
        $('#lightbox').hide();
      $('.gallery-container').removeClass('lightbox-active');
    });

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 感谢您的回复。是的,我能够让它与 body 标签一起工作。如果我想为我的事件处理程序使用类选择器,我似乎认为我需要制作一个静态 div。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 2022-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
相关资源
最近更新 更多