You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

封装在form中的W3School Accordion点击头部触发页面刷新,如何解决?

解决Form内Accordion按钮点击导致页面刷新的问题

问题出在你form里的那些折叠面板头部按钮上——HTML里的<button>元素在form标签内时,默认的type属性是submit,所以每次点击这些按钮,浏览器都会触发表单的提交行为,自然就会刷新页面啦。

给你两种简单有效的解决办法:

方法一:给折叠按钮添加type="button"属性(推荐)

直接明确告诉浏览器,这些按钮是普通功能按钮,不是提交按钮。修改你的按钮代码,加上type="button"即可:

<form name="formone" method="post" action="file.php">
  <!-- 添加type="button" -->
  <button type="button" onclick="myFunction('Demo1')" class="w3-btn w3-block w3-black w3-left-align">Vehicle</button>
  <div id="Demo1" class="w3-container w3-hide">
    <input type="checkbox" name="vehicle" value="Bike"> Bike<br>
    <input type="checkbox" name="car" value="Car"> Car<br>
  </div>
  <!-- 同样添加type="button" -->
  <button type="button" onclick="myFunction('Demo2')" class="w3-btn w3-block w3-black w3-left-align">Distance</button>
  <div id="Demo2" class="w3-container w3-hide">
    <input type="checkbox" name="distance" value="m"> Metre<br>
    <input type="checkbox" name="distance" value="km"> KM<br>
  </div>
  <br>
  <button type="submit" name="submit">Submit</button>
</form>

<script>
function myFunction(id) {
  var x = document.getElementById(id);
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }
}
</script>

方法二:在点击事件中阻止默认提交行为

如果不想修改按钮的type属性,也可以通过JavaScript阻止默认事件。有两种方式:

方式1:在onclick事件里返回false

修改按钮的onclick属性,加上return false:

<button onclick="myFunction('Demo1'); return false;" class="w3-btn w3-block w3-black w3-left-align">Vehicle</button>

方式2:在函数内调用preventDefault()

修改你的myFunction,接收事件参数并阻止默认行为:

<button onclick="myFunction(event, 'Demo1')" class="w3-btn w3-block w3-black w3-left-align">Vehicle</button>

对应的JavaScript:

function myFunction(event, id) {
  // 阻止默认提交行为
  event.preventDefault();
  var x = document.getElementById(id);
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }
}

个人更推荐第一种方法,因为它最直观,从根源上避免了按钮被识别为提交按钮,代码也更简洁。

内容的提问来源于stack exchange,提问作者Athirah Hazira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:31:54