关于javascript中document的问题:为空或不是对象

写一个全选checkbox的js,用下面这段代码:

function selAll() {
        var len = document.Content_form.elements.length;
        var i;
        if (document.Content_form.ck.checked) {
            for (i = 0; i < len; i++) {
                if (document.Content_form.elements[i].type == "checkbox") {
                    documentContent_form.elements[i].checked = true;
                }
            }
        }
        else {
            for (i = 0; i < len; i++) {
                if (document.Content_form.elements[i].type == "checkbox") {
                    document.Content_form.elements[i].checked = false;
                }
            }
        }

始终报错:document.Content_form.elements为空或不是对象,非常确定不是ID写错的问题,后来在页面打开源代码发现这么一段:

 var theForm = document.forms['Content_form'];
 if (!theForm) {
      theForm = document.Content_form;
 }

没有报错,遂将代码修改如下:

function selAll() {
 var theForm = document.forms['Content_form'];
 if (!theForm) {
      theForm = document.Content_form;
 }
        var len = theForm.elements.length;
        var i;
        if (theForm.elements['ck'].checked) {
            for (i = 0; i < len; i++) {
                if (theForm.elements[i].type == "checkbox") {
                    theForm.elements[i].checked = true;
                }
            }
        }
        else {
            for (i = 0; i < len; i++) {
                if (theForm.elements[i].type == "checkbox") {
                    theForm.elements[i].checked = false;
                }
            }
        }
    }

 

这样一来居然成了,实在很不理解为什么非要这样写?另外发现有时候js代码要先于网页加载执行,如何控制呢?

你可能感兴趣的:(关于javascript中document的问题:为空或不是对象)