日期:2014-05-16  浏览次数:20391 次

js清空file类型的值得几种方法,不同浏览器下
在firefox下使用js清空file控件的value非常简单, 即:obj.value=""; 就可以了,但在ie下,由于出于安全等方面考虑,file的value被设为了只读,所以js对其不能直接地控制,因此我们只能使用一些变通的方法来解 决,网上对此也有好些方法,在此我谈谈自己认为最好的几种。

下面以上传文件格式限制(只对扩展名判断)这一实例来说明。

1、file控件由HTML生成

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-

transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function CheckUpLoadFile(obj) {
DenyExt = "exe|cmd|jsp|php|asp|aspx|html|htm";
var FileExt = "";
FileExt = obj.value.substr(obj.value.lastIndexOf(".") + 1).toLowerCase();
if (DenyExt.indexOf(FileExt) != -1) {
alert("You can't upload the file of the types:" + DenyExt);
if (!window.addEventListener) {     
//IE 关键代码在这里!!!
//方法一(此方法最佳!):
obj.outerHTML+='';
//方法二:
//       var newObj= obj.cloneNode(true);
//       newObj.value=''; // 设置新控件value为空
//       obj.parentNode.replaceChild(newObj, obj);

} else {
//非IE
obj.value = "";
return false;
}

}
}
</script>
<title>无标题文档</title>
</head>
<body>
<span id="attachments_span">
<input type="file" name="myfile" onchange="CheckUpLoadFile(this);">
</span>
</body>
</html>
2、file控件由JS动态生成

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-

transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<script>  
function addUploadField(name, parentId) {  
var f = document.createElement("input");  
f.type = "file";  
f.name = name;  
if (window.addEventListener) { // Mozilla, Netscape, Firefox     
f.addEventListener("change", function() {  
CheckUpLoadFile(f, parentId);  
}, false);  
} else { // IE     
f.attachEvent('onchange', function() {  
CheckUpLoadFile(f, parentId);  
});  
}  
f.size = 30;  
p = document.getElementById(parentId);  
p.appendChild(document.createElement("br"));  
p.appendChild(f);  
}  

function CheckUpLoadFile(obj) {  
DenyExt = "exe|cmd|jsp|php|asp|aspx|html|htm";  
if (obj.value == "") {
return false;
}
var FileExt = "";  
FileExt = obj.value.substr(obj.value.lastIndexOf(".") + 1).toLowerCase();  
if (DenyExt.indexOf(FileExt) != -1) {  
alert("You can't upload the file of the types:" + DenyExt);  
if (!window.addEventListener) {      
//IE 关键代码在这里!!!
obj.select();  
document.execCommand('Delete');  
obj.blur();  
//obj.outerHTML+=''; 此方法虽然很安全,但可惜在此不能使用
return false;  
} else {  
//非IE  
obj.value = "";  
return false;  
}  

}  
}  
</script>  
<title>无标题文档</title>  
</head>  
<body>  
<span id="attachments_span">&n