简体   繁体   中英

close div when clicking button inside div

I have a div that loads information from another page when someone clicks on a thumbnail image on the same page.

Currently, when a person clicks on a thumbnail image, the div #dynamic at the top of the page will load and display information from another page. I want to be able to allow users to click on a close button which i have given a class button_close for them to close the div instead of clicking anywhere within it. The button is being displayed within the #dynamic div as well.

$(document).ready(function(){
   $('nav.main > a').click(function(e){
    e.preventDefault();
    $("#dynamic").load($(this).attr('href') + " .product_content", ()=>{ window.scrollTo(0, 0) }).fadeIn('slow');
   });
      $(".button_close").click(function(){
          $(".product_container").html ('');
      });
  });

Since your close_button is being generated dynamically, you can use the following

$('body').on('click', '.button_close', function(){
    $('#dynamic').html('');
});

A simple example

<!DOCTYPE html>
<html>
<body>

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script>
function loadDiv() {
    $('#dynamic').html('<p>Some content loaded from another page</p><div class="button_close">Close Me</div>');
}

$('body').on('click', '.button_close', function(){
    $('#dynamic').html('');
});
</script>

<div id="dynamic"></div><br><br>
<button onclick="loadDiv()">Load Div</button>

</body>
</html>

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