JS 动态删除表单项时出现的问题

思路是在表单提前时,如果文件控件没有选择文件,则自动删除这些控件,再提交表单。

但是在实际操作中报错,不知道是什么原因,烦请指教改正,谢谢。
完整代码如下,浏览器第21行报错,已经注释出来。

<!DOCTYPE html>
<html>
    <head>
		<meta charset="utf-8" />
        <title>首页</title>
		<style>
		</style>
    </head>
    <body>
		<form method="POST" enctype="multipart/form-data">
			<input type="file" name="file[]" />
			<input type="file" name="file[]" />
			<input type="file" name="file[]" />
			<input type="submit" />
		</form>
		<script>
			document.getElementsByTagName('form')[0].addEventListener(
				'submit',
				function(e){
					for(var inputs=document.getElementsByName('file[]'), i=0, l=inputs.length; i<l; i++){
						try{
							if(inputs[i].files.length===0){ //Cannot read property 'files' of undefined.
								inputs[i].parentNode.removeChild(inputs[i]);
							}
						}catch(ex){
							alert(ex.message);
						}
					}
					e.preventDefault();
				},
				false
			);
		</script>
<?php
	echo '<pre>';
	print_r($_FILES);
	echo '</pre>';
?>		
    </body>
</html>


丢矢矣
浏览 1848回答 0
0回答
打开App,查看更多内容
随时随地看视频慕课网APP