简体   繁体   中英

Javascript error on IE8 and IE9

I'm getting '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)  
        }
    }
}

Im not sure why above code throws a javascript error 'this.0.files.0' is null or not an object

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

To get the filename you can do:

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

or simply:

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

Full code:

$(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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM