JavaScript出现Cannot read property 'submit' of undefined错误,求解决
解决"Cannot read property 'submit' of undefined"错误
你遇到的Uncaught TypeError: Cannot read property 'submit' of undefined错误,核心原因是代码里的document.openShiftForm没有找到对应的表单元素,导致调用submit()方法时触发了未定义错误。
问题根源
虽然你给表单设置了name="openShiftForm",但直接通过document.表单名称的方式访问DOM元素并不总是可靠的:
- 如果DOM还未完全加载完成就执行了JS代码,会找不到元素
- 页面中存在同名的全局变量或其他元素时,会引发命名冲突
修复方案
这里提供几种可靠的解决方法,任选其一即可:
方案1:给表单添加ID,用getElementById获取
修改你的PHP输出表单的代码,给<form>标签加上id="openShiftForm":
echo '<form action="" method="post" enctype="multipart/form-data" name="openShiftForm" id="openShiftForm">';
然后将JavaScript中所有的document.openShiftForm.submit()替换为:
document.getElementById('openShiftForm').submit();
方案2:通过document.forms集合访问表单
不需要修改HTML,直接把JS里的表单调用代码替换为:
document.forms['openShiftForm'].submit();
document.forms是专门存储页面中所有表单的集合,通过表单的name属性查找,比直接访问document属性更稳定。
方案3:点击按钮时直接传递表单对象
修改按钮的onclick事件,将当前表单对象传递给函数:
echo '<button type="button" onclick="addLatlng(this.form)" class="btn btn-danger btn-lg" name="openShift" value="1">'.$shiftTypeArray[intval($_SESSION['openShiftType'])]['name'].' open shift</button>';
然后更新addLatlng函数,接收表单参数并使用:
function addLatlng(form) { var options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }; function success(pos) { var crd = pos.coords; console.log(crd.latitude); console.log('Your current position is:'); console.log(`Latitude : ${crd.latitude}`); console.log(`Longitude: ${crd.longitude}`); console.log(`More or less ${crd.accuracy} meters.`); document.getElementById('latlng').value = crd.latitude + "-" + crd.longitude; form.submit(); }; function error(err) { console.warn(`ERROR(${err.code}): ${err.message}`); document.getElementById('latlng').value = "ERROR" + "-" + err.message; form.submit(); }; navigator.geolocation.getCurrentPosition(success, error, options); }
这种方法完全避免了在DOM中查找表单的步骤,是最直接且不易出错的方式。
内容的提问来源于stack exchange,提问作者Malta
相关产品推荐
相关产品推荐

