简体   繁体   English

使用 jQuery 单击隐藏/显示按钮时页面重新加载

[英]Page reloads on hide/show button click using jQuery

I'm using jQuery to show/hide a div by clicking on the show/hide buttons.我正在使用 jQuery 通过单击显示/隐藏按钮来显示/隐藏div However, my code doesn't work because every time it returns to the way it was before when I click on my buttons.但是,我的代码不起作用,因为每次它返回到我单击按钮时的状态时。 I'm almost sure that this is due to a page reload, because every time I click on a button it reloads the page.我几乎可以肯定这是由于页面重新加载造成的,因为每次我点击一个按钮时它都会重新加载页面。
Does anybody know what could be the reason behind this?有谁知道这背后的原因是什么?

Here is the important chunk of code:这是重要的代码块:

<form role="form" method="post" action="./something.php">
  ...
  <button id="hidemultmachines" onclick="$('#multmachines').hide(); $(this).hide(); $('#showmultmachines').show();">
    Hide section below ...
  </button>
  <button id="showmultmachines" onclick="$('#multmachines').show(); $(this).hide(); $('#hidemultmachines').show();">
    ... Create multiple entries
  </button>
  <div id="multmachines">
    ...
  </div>
  <div>
    <div>
      <input type="hidden" name="total" value="{ $smarty.section.i.total }">
      <button type="submit" name="Submit" value="Save">Save</button>
    </div>
  </div>
</form>

And this is my jQuery code in the header:这是我在标题中的 jQuery 代码:

$(document).ready(function(){
    $('#hidemultmachines').hide();
    $('#multmachines').hide();
}

When I put the buttons outside the form it works.当我将按钮放在表单之外时,它可以工作。 Why?为什么?

That's because your button elements have no type specified, and by default button elements have their type set to "submit".那是因为您的button元素没有指定type ,默认情况下button元素的type设置为“提交”。 When you click one of the buttons, they attempt to submit your form.当您单击其中一个按钮时,它们会尝试提交您的表单。 Simply specifying a type of "button" will fix this:只需指定一种“按钮” type即可解决此问题:

<button type="button" class="close" id="hidemultmachines" onclick="..."></button>

A couple of things here:这里有几件事:

1) It would be best to separate the HTML from the jQuery. 1) 最好将 HTML 与 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. 2) 按钮的默认行为是提交表单,这意味着如果没有表单操作,它将刷新页面。 This can be fixed with preventDefault()这可以通过 preventDefault() 解决

To sum this up in code:用代码总结一下:

HTML HTML

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

JS: JS:

$(document).ready(function() {
$("#hidemultmachines").on("click", function(e) {
  e.preventDefault();
  $('#multmachines').hide();    
  $(this).hide();
  $('#showmultmachines').show();
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM