6

我得到 'this.0.files.0' is null or not an object error on IE8 and IE9 and Chrome and Mozila don't throw any errors 。

$(function()) {
    var fileType = ['txt' , 'csv' ];
    $('.input_file').find('input [type = "file" ]').live('change', function (e)) {
        $this = $(this) 
        var ext = $this.val() === " " ? " " : this.value.match(/\.(.+)$/)[1];
        if($this.val()) {
            $this.parent().find('label').text.($this[0].files[0].name)  
        }
    }
}

我不确定为什么上面的代码会引发 javascript 错误 'this.0.files.0' is null or not an object

4

2 回答 2

11

IE < 10 不支持 html5 fileapi,即不HTMLInputElement.FileList,您必须解析HTMLInputElement.value才能获取文件名。

于 2013-04-27T18:46:49.607 回答
1

要获取文件名,您可以执行以下操作:

var filename = $this[0].files ? $this[0].files[0].name : $this[0].value.match(/[^\/\\]*$/)[0];

或者简单地说:

$this[0].value.match(/[^\/\\]*$/)[0];

完整代码:

$(function()) {
    var fileType = ['txt' , 'csv' ];
    $('.input_file').find('input [type = "file" ]').live('change', function (e)) {
        $this = $(this) 
        var ext = $this.val() === " " ? " " : this.value.match(/\.(.+)$/)[1];
        if ($this.val()) {
            var filename = $this[0].files ? $this[0].files[0].name : $this[0].value.match(/[^\/\\]*$/)[0];
            $this.parent().find('label').text.($this[0].files[0].name);
        }
    }
}
于 2015-05-06T16:39:11.363 回答