Tuesday, October 23, 2007

'document.getElementById(...)' 为空或不是对象


<div id="form_div"></div>
<script type="text/javascript">
var urls = 'http://www.google.com/search?q=test';
var fragment = document.createDocumentFragment();
var form = document.createElement('form');
var input = document.createElement('input');
var submit = document.createElement('input');
form.action = urls;
form.setAttribute('method', 'post'); // 这里不能设置为get方法,因为GET方法会将action中原有的参数过滤后加个表单里的参数,如text1=value。
input.setAttribute('value', "value");
input.setAttribute('type', "text");
input.setAttribute('name', "text1");
input.setAttribute('size', "50");
submit.setAttribute('type', "submit");
form.appendChild(input); // node.appendChild(newNode)方法执行后返回的值是newNode。
form.appendChild(document.createElement('br'));
form.appendChild(submit);
fragment.appendChild(form);
try
{
document.getElementById('form_div').appendChild(fragment);
}
catch (e)
{
document.write(e.message);
//document.getElementById("form_div") => null
//FF: document.getElementById("form_div") has no properties
//IE: 'document.getElementById(...)' 为空或不是对象
//document.write(e.description);
//IE: 'document.getElementById(...)' 为空或不是对象
}
</script>

必须将给以上代码写入body标签中才能正确运行。
不然这段代码在浏览器解析时生成的DOM中,这一段javascript被置于head中,而form_div这个Element则会出现在浏览器生成的DOM的body中,而页面js被执行时,因为这个Element在执行语句之后,所以就会找不到此Element,从而报对象为空或不是对象这个错误。

No comments :