我使用2个函数输入文件foto进行有效扩展,并用foto的名称替换label
html代码:
<input class="foto" type='file' name='propic' id="aa" class="required" value="<?php echo "$FOTO"; ?>" onchange="pressed()"><label style="font-weight:normal; width:80px; overflow:hidden; text-overflow:ellipsis;" id="fileLabel"><?php echo "$FOTO"; ?></label>
javascript代码:
<script type="text/javascript">
var a = document.getElementById('aa');
window.pressed = function(){
if(a.value == "")
{
fileLabel.innerHTML = "Choose file";
}
else
{
var theSplit = a.value.split('\\');
fileLabel.innerHTML = theSplit[theSplit.length-1];
}
};
a.onchange = function(e){
var ext = this.value.match(/\.([^.]+)$/)[1];
switch(ext)
{
case 'jpg':
case 'jpeg':
case 'png':
break;
default:
alert('File is not valid!');
this.value='';
}
};
</script>
只有一个功能正常工作,即有效文件扩展功能。如何使其他功能工作?
答案 0 :(得分:1)
请尝试:
<script type="text/javascript">
var a = document.getElementById('aa');
var fileLabel = document.getElementById('fileLabel');
updateLabel = function(){
if(a.value == "")
{
fileLabel.innerHTML = "Choose file";
}
else
{
var theSplit = a.value.split('\\');
fileLabel.innerHTML = theSplit[theSplit.length-1];
}
};
validateExtension = function(e){
var ext = this.value.match(/\.([^.]+)$/)[1];
switch(ext)
{
case 'jpg':
case 'jpeg':
case 'png':
break;
default:
alert('File is not valid!');
this.value='';
}
};
a.addEventListener('change',validateExtension,false);
a.addEventListener('change',updateLabel,false);
</script>
并从html代码中删除onchange
。