简体   繁体   中英

can't hide bootstrap modal with jquery

My modal appears when I click a small img with class modalphotos However when i click the image to close it, the event handler doesn't respond. The modal doesn't hide and the alert doesn't pop up. Does anybody know whay i'm doing wrong?

  //show modals
  $('.modalphotos img').on('click', function () {
    $('#modal').modal({
        show:true,
    })

    var mysrc = this.src;
    $('#modalimage').attr('src', mysrc);
    $('#modalimage').on('click', function () {
        alert('clicked');
        $('#modal').modal('hide');
    })//hide modal
  });//show modal

in the HTML i have a section with id modal

            <!-- Modal -->
            <section id="modal" class="modal fade">
                <div class="modal-body">
                    <img id="modalimage" src="">
                </div><!-- modal-body -->
            </section>

And in an aside i have some photo's

    <aside class="selectie">
            <h2>Een kleine selectie</h2>
            <div class="modalphotos phtotgrid clearfix">
                <img src="images/misc/huisje1.jpg" width="20%" height="20%">
                <img src="images/misc/huisje2.jpg" width="20%" height="20%">
                <img src="images/misc/huisje3.jpg" width="20%" height="20%">
            </div>
        </aside>

The use would be that when i click a photo i get the modal showing the large version of the image

Nesting event handlers is a bad idea. Can you also share the HTML so it gives a better idea what you are trying to achieve.

 $('.modalphotos img').on('click', function () { 
      $('#modal').modal({ 
           show:true,
           keyboard:true //Enables user to press 'Esc' and close modal 
      }); 
 }); 
 $('#modalimage').on('click', function () { 
      $('#modal').modal('hide'); 
 }); 

As I said before nesting events is not a good idea. So we separate the events.

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