IE6、7的JavaScript用document.getElementsByName取表单控件的值会出错。

解决办法:表单控件加ID属性,id和name同样定义即可!

<div id="test"></div>
<script type="text/JavaScript">
var _input;
var _test = document.getElementById('test');
_input = document.createElement('input');
	_input.type = 'text';
	_input.name = 'test[1]';
	_input.value = 'test1';
_test.appendChild(_input);
_input = document.createElement('input');
	_input.type = 'text';
	_input.name = 'test[2]';
	_input.id = 'test[2]';
	_input.value = 'test2';
_test.appendChild(_input);
try{
	alert(document.getElementsByName('test[1]')[0].value);
}catch(e){
	alert(e.toString());
}
alert(document.getElementsByName('test[2]')[0].value);
</script>

2 Comments

  • david.inv

    document.write(‘<input type=”test” name=”test[1]”>’);

    是可以的

    Reply
  • 王炜

    只有 document.createElement 出来的控件有 BUG

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *