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

使用jQuery提交表单时#register_form无法隐藏,无报错求排查

表单提交后未隐藏的问题解决

提交id为#register_form的表单时,表单未按预期隐藏,控制台无报错,且表单为内联式提交(提交过程在当前页面完成)。相关代码如下:

原JS代码

$("#register_form").submit(function(e) {
  $(".client_hide").hide();
  $("#post_text").show();
});

原HTML代码

<form method="POST" class="client_hide form-horizontal" action="client3.php" id="register_form">
  <div class="button">
    <button type="submit" name="register_submit">Submit</button>
  </div>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

问题原因

表单提交的默认行为是触发页面跳转(即使action指向当前页面,也会导致页面刷新)。你的隐藏代码虽然会执行,但页面随即刷新,导致隐藏效果无法保留。

解决方案

在表单提交事件中阻止默认提交行为,避免页面刷新,同时根据需求选择是否保留数据提交功能:

1. 仅隐藏表单(不提交数据)

修改JS代码,添加e.preventDefault():

$("#register_form").submit(function(e) {
  // 阻止表单默认提交,避免页面刷新
  e.preventDefault();
  $(".client_hide").hide();
  $("#post_text").show();
});

2. 隐藏表单+异步提交数据

如果需要完成数据提交,同时保留页面不刷新,使用AJAX异步提交:

$("#register_form").submit(function(e) {
  e.preventDefault();
  $(".client_hide").hide();
  $("#post_text").show();

  // 异步提交表单数据到后端
  $.ajax({
    url: $(this).attr("action"),
    type: $(this).attr("method"),
    data: $(this).serialize(), // 序列化表单数据
    success: function(res) {
      // 提交成功后的逻辑,比如提示用户
      console.log("提交成功");
    },
    error: function(err) {
      // 提交失败后的逻辑
      console.error("提交失败", err);
    }
  });
});

这样修改后,表单提交时会先隐藏自身、显示#post_text,同时不会刷新页面,数据提交也能正常完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:45:46