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

为何未被调用的JavaScript函数导致网站持续刷新?

页面自动刷新问题排查与修复

问题根源

你代码里的全局变量location和浏览器内置的window.location重名了。当页面加载执行var location = ""时,实际是修改了浏览器的导航对象window.location,给它赋值空字符串等价于设置location.href = "",这会直接触发页面重新加载,所以只要代码存在,页面就会不断自动刷新。

同时代码还有其他几个问题会导致逻辑失效甚至报错:

  • const list_job_form是常量,函数内重新赋值会抛出语法错误
  • 获取DOM元素后没有取.value属性,直接判断元素对象是否为空字符串永远不成立
  • for...in遍历数组拿到的是索引而非元素值,校验逻辑错误
  • 若按钮在<form>内,默认是submit类型,点击会触发表单提交刷新页面

修复方案

  1. 重命名冲突变量:把全局变量location改成其他名称,比如jobLocation
  2. 调整变量声明类型:将const list_job_form改为let,允许后续重新赋值
  3. 获取输入框实际值:调用document.getElementById()后加上.value获取输入内容
  4. 修正数组遍历方式:用for...of遍历数组元素,替代遍历索引的for...in
  5. 阻止表单默认提交:给按钮添加type="button",或在函数末尾返回false

修复后的完整代码

JavaScript部分

var typeofwork = ""
var jobLocation = "" // 重命名避免与window.location冲突
var pay = ""
var timeframe = ""
var email = ""
var phone = ""
var description = ""
var specialrequirements = ""

let list_job_form = [typeofwork, jobLocation, pay, timeframe, email, phone, description, specialrequirements];

var list_job_form_filled = true

function list_job_submit() {
  // 获取输入框的value值
  typeofwork = document.getElementById("list_job_typeofwork").value;
  jobLocation = document.getElementById("list_job_location").value;
  pay = document.getElementById("list_job_pay").value;
  timeframe = document.getElementById("list_job_timeframe").value;
  email = document.getElementById("list_job_email").value;
  phone = document.getElementById("list_job_phone").value;
  description = document.getElementById("list_job_description").value;
  specialrequirements = document.getElementById("list_job_specialrequirements").value;
  
  list_job_form = [typeofwork, jobLocation, pay, timeframe, email, phone, description, specialrequirements];

  list_job_form_filled = true; // 每次校验前重置状态
  // 用for...of遍历数组元素
  for (const item of list_job_form) {
    console.log(item);
    if (item === "") {
      list_job_form_filled = false;
    }
  }
  
  // 若按钮在form内,返回false阻止默认提交行为
  return false;
}

HTML按钮部分

<button id="job_listing_submit_button" type="button" onclick="list_job_submit()">
  Submit
</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:12:52