Javascript 对象在 IE 中为 null 或不是 object

Javascript object is null or not object in IE

本文关键字:object null 中为 对象 IE Javascript      更新时间:2023-09-26

我有一个表单,javascript在其中添加了复选框,当表单提交时,它会检查复选框是否已被选中。这在Firefox或Chrome中工作正常,但在IE7或8中,它会导致错误document.myform.mycheckbox.checked为null或不是对象。

var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "mycheckbox";
checkbox.value= 291;
var div = document.getElementById("addcb");
div.appendChild(checkbox);
checkbox.checked = false;

在表单标签中,我有onSubmit="return CheckForm();",它在Firefox或Chrome中工作正常,但在IE7或8中,它提交表单而不检查表单或其他表单对象。

if (document.myform.mycheckbox.checked == false){
    errorMsg += "'n'tAgree 't- Please Click I Agree Checkbox";
}
//If there is aproblem with the form then display an error
if ((errorMsg != "") || (errorMsgLong != "")){
    msg = "_______________________________________________________________'n'n";
    msg += "The form has not been submitted because there are problem(s) with the form.'n";
    msg += "Please correct the problem(s) and re-submit the form.'n";
    msg += "_______________________________________________________________'n'n";
    msg += "The following field(s) need to be corrected: -'n";
    errorMsg += alert(msg + errorMsg + "'n" + errorMsgLong);
    return false;
}
return true;

我使用开发人员工具创建了一个报告错误的 Brakpoint:

document.myform.mycheckbox.checked is null or not an object

在创建它时,也要给它一个 ID

checkbox.id = "mycheckbox";

然后要找到它,请执行

if (document.getElementById("mycheckbox").checked == false)