这是我使用document.ready
函数的html和javascript代码
这里的HTML脚本......
<textarea id="recipients" name="recipients" class="form-control"></textarea>
<input name="file" type="file" id="files" class="form-control" value="">
<a id="fetch_number" class="btn btn-primary btn-sm" href="">pull text file</a>
以下是javascript代码:
$(document).ready(function() {
$('#fetch_number').on('click', function() {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
if (window.File && window.FileReader && window.FileList && window.Blob) {
var text_file = document.getElementById('files');
var files = text_file.files;
var file = files[0];
var extension = file.name.split('.').pop();
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output = output.split("/\r\n|\n/");
var string = '';
for (var i=0; i < output.length; i++) {
var data = allTextLines[i].split(',');
string = data[1] + ',';
}
return string;
$("#recipients").text(string);
};
} else {
alert('The File APIs are not fully supported by your browser.');
}
});
});
这是javascript代码我不知道该怎么办如果我不浏览任何文本文件它会给我(!files.length)
的回复
,但我不知道别人为什么不工作。
答案 0 :(得分:0)
你遇到了问题,因为
return string;
return
尝试这样的事情
function readTextFile(file, callback, encoding) {
var reader = new FileReader();
reader.addEventListener('load', function (e) {
callback(this.result);
});
if (encoding) reader.readAsText(file, encoding);
else reader.readAsText(file);
}
function fileChosen(input, output) {
if (input.files && input.files[0]) {
readTextFile(
input.files[0],
function (str) {
output.value = str;
}
);
}
}
$('#files').on('change', function () {
fileChosen(this, document.getElementById('recipients'));
});
&#13;
<textarea id="recipients" name="recipients" class="form-control"></textarea>
<input name="file" type="file" id="files" class="form-control" value="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
&#13;