我試圖自動提示用戶上傳 CSV 檔案,然后我打算訪問其中的資料,但我無法做到這一點。我究竟做錯了什么?input.name 始終未定義,查看整個物件不會提供任何相關詳細資訊。
此查詢的來源主要來自此問題的答案Open file dialog box in JavaScript。我試圖完全用 javascript 而不是 HTML 來實作這一點。
提琴手
$(document).ready(function() {
var input = $(document.createElement('input'));
input.attr("type", "file");
input.on('change',function(){
alert(JSON.stringify(input.name, null, 4));
alert(JSON.stringify(input, null, 4));
});
input.trigger('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
uj5u.com熱心網友回復:
input是 的回傳值$()。它是一個 jQuery 物件而不是一個 DOM 物件。要訪問name的底層DOM物件的屬性,使用的prop方法。
input.prop('name')
uj5u.com熱心網友回復:
我終于讓它作業了。這是解決方案
$(document).ready(function() {
var input = $(document.createElement('input'));
input.attr("type", "file");
input.on('change', function() {
var csvFile = input[0].files[0];
var ext = csvFile.name.split(".").pop().toLowerCase();
if (ext != "csv") {
alert('upload csv');
return false;
}
if (csvFile != undefined) {
reader = new FileReader();
reader.onload = function(e) {
var data = $.csv.toObjects(e.target.result);
alert(JSON.stringify(data, null, 4));
$.each(data, function(index, val) {
//do something with each row of data val.ColumnName
});
}
reader.readAsText(csvFile);
}
});
input.trigger('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.21/jquery.csv.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396450.html
標籤:javascript 查询
