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

4
我正在使用jQuery来通过点击显示/隐藏按钮来显示/隐藏一个
。 但是,我的代码不起作用,因为每次我点击按钮时,它都会返回到之前的样子。我几乎确定这是由于页面重新加载导致的,因为每次我点击按钮时,它都会重新加载页面。
有人知道这背后可能的原因吗?
这是关键代码块:
<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>

这是我在头部的jQuery代码:

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

当我把按钮放在表单外面时,它就能正常工作。为什么呢?

3
像这样使用onclick是一个非常不好的做法。 在你的“ready”部分添加以下内容:$('#hidemultmachines').click(function() { ... 在这里编写你的点击代码... } ); - Kinnza
因为表单中的按钮默认会创建一个提交并重新加载页面。将其放置在“click”事件中并使用“e.preventDefault()”。或者将您的按钮放在表单之外。或者更改“type”。 - Spencer Wieczorek
1
已经有人帮助你了 - 尽管使用 onClick 不是一个好的做法 - 但你也可以在 onclick 中的 JavaScript 命令字符串末尾添加 ;return false;,这样可以阻止提交。这本质上是"停止冒泡此事件"。 - Jason
2个回答

11

这是因为你的 button 元素没有指定 type 属性,默认情况下,button 元素的 type 属性被设置为 "submit"。当你点击其中一个按钮时,它们会尝试提交表单。只需指定一个 type 属性为 "button" 即可解决此问题:

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

真正的英雄就在这里! - Jerome

1

这里有几点需要注意:

1)最好将HTML和jQuery分开。 2)按钮的默认行为是提交表单,如果没有表单操作,这意味着它会刷新页面。可以通过preventDefault()来解决。

代码总结如下:

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();
});
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接