如何在eventlistener之外到达变量?

时间:2013-06-18 21:26:20

标签: javascript jquery filereader

我想制作一个js代码,用于生成有关所选图片的列表,其中包含当前图片的缩略图,文件名和文件大小。但是有些错误,因为我无法访问文件名和文件大小,因为eventListener没有看到它。任何解决方案?

$('#media_uploader').change( function() {
    var files = document.getElementById("media_uploader").files;
    var output = document.getElementById("info");
    output.innerHTML = '';
    for(var i = 0; i< files.length; i++)
    {
        var file = files[i];
        if( !file.type.match('image') )
          continue;

        var picReader = new FileReader();
        picReader.addEventListener("load",function(event){
            var picFile = event.target;
            var div = document.createElement("div");
            div.innerHTML = '<img src="' + picFile.result + '" />';

            var lineNode = document.createElement('div');
                lineNode.setAttribute('class','uploaded_file_line');

            var fileThbDivNode = document.createElement('div');
                fileThbDivNode.setAttribute('class','uploaded_file_thb');
            fileThbDivNode.appendChild(div);
            lineNode.appendChild( fileThbDivNode );

            var fileNameDivNode = document.createElement('div');
                fileNameDivNode.setAttribute('class','uploaded_file_name');
            var fileNameNode = document.createElement('input');
                fileNameNode.setAttribute('value',picFile.name);
            fileNameDivNode.appendChild( fileNameNode );
            lineNode.appendChild( fileNameDivNode );

            var fileExtensionDivNode = document.createElement('div');
                fileExtensionDivNode.setAttribute('class','uploaded_file_extension');
            var fileExtensionNode = document.createElement('span');
                fileExtensionNode.innerHTML = "JPG";
            fileExtensionDivNode.appendChild( fileExtensionNode );
            lineNode.appendChild( fileExtensionDivNode );

            var fileSizeDivNode = document.createElement('div');
                fileSizeDivNode.setAttribute('class','uploaded_file_size');
            var fileSizeNode = document.createElement('span');
                fileSizeNode.innerHTML = Number((((picFile.size)/1024)/1024).toFixed(3)) + " Mbytes";
            fileSizeDivNode.appendChild( fileSizeNode );
            lineNode.appendChild( fileSizeDivNode );

            var clearDivNode = document.createElement('div');
                clearDivNode.setAttribute('class','clear');
            lineNode.appendChild( clearDivNode );

            output.appendChild( lineNode );
        });
        picReader.readAsDataURL(file);
    }
});

2 个答案:

答案 0 :(得分:1)

尝试在更改函数

之外声明var文件

答案 1 :(得分:0)

我觉得这样的事可能适合你

var stuffIcannotSee;

var my_func=function(importStuff){
      return function(e){
          alert(importStuff + "This is now in the context of the function");
      };
}(stuffIcannotSee);

$('#media_uploader').change( my_func);