Page reloads on hide/show button click using jQuery

前端 未结 2 509
暖寄归人
暖寄归人 2020-12-11 21:33

I\'m using jQuery to show/hide a div by clicking on the show/hide buttons. However, my code doesn\'t work because every time it returns to the way it was before

相关标签:
2条回答
  • 2020-12-11 22:19

    A couple of things here:

    1) It would be best to separate the HTML from the jQuery. 2) The default behavior for a button is to submit a form, which means it will refresh the page if there is no form action. This can be fixed with preventDefault()

    To sum this up in code:

    HTML

    <button class="close" id="hidemultmachines" >Hide section below <img alt="Close" width="35" height="35" src="../images/close.png"> </button>
    

    JS:

    $(document).ready(function() {
    $("#hidemultmachines").on("click", function(e) {
      e.preventDefault();
      $('#multmachines').hide();    
      $(this).hide();
      $('#showmultmachines').show();
    });
    });
    
    0 讨论(0)
  • 2020-12-11 22:22

    That's because your button elements have no type specified, and by default button elements have their type set to "submit". When you click one of the buttons, they attempt to submit your form. Simply specifying a type of "button" will fix this:

    <button type="button" class="close" id="hidemultmachines" onclick="..."></button>
    
    0 讨论(0)
提交回复
热议问题