Javascript 如何导入本地文本文件以使用FileReader()填充下拉列表
我有点陷入了一个问题,我正试图将一个文本文件从本地计算机导入JavaScript,并根据文本文件填充HTML下拉列表。我花了很多时间研究关于堆栈溢出的类似问题,但还没有找到解决问题的方法。以下是文本文件外观的示例:Javascript 如何导入本地文本文件以使用FileReader()填充下拉列表,javascript,html,Javascript,Html,我有点陷入了一个问题,我正试图将一个文本文件从本地计算机导入JavaScript,并根据文本文件填充HTML下拉列表。我花了很多时间研究关于堆栈溢出的类似问题,但还没有找到解决问题的方法。以下是文本文件外观的示例: Dogs - Blue Dog Black Doggo Random Doggo Cats - Neon cat Grumpy cat Potato cat function LoadTxtFile(p) { var AllTxtdata
Dogs -
Blue Dog
Black Doggo
Random Doggo
Cats -
Neon cat
Grumpy cat
Potato cat
function LoadTxtFile(p) {
var AllTxtdata = '';
var FileRead = new FileReader();
FileRead.onload = function (e) {
if (FileRead.readyState === 2) {
AllTxtdata = FileRead;
var lines = FileRead.result.split('\n').map(function (line) {
return line.trim();
});
var select = $("select[name=MySelect]");
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function (line) {
if (line.endsWith(" -")) {
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
select.append("<optgroup id'" + currentGroup + "' label='" + currentGroup + "'>");
} else if (line === "") {
select.append("</optgroup>");
} else {
select.append("<option type='checkbox' id='" + (currentGroup + optionCounter) + "' name'"
+ (currentGroup + optionCounter) + "' value='"
+ line + "'>" + line + "</option>");
}
});
};
}
}
以下是我的JS的外观:
Dogs -
Blue Dog
Black Doggo
Random Doggo
Cats -
Neon cat
Grumpy cat
Potato cat
function LoadTxtFile(p) {
var AllTxtdata = '';
var FileRead = new FileReader();
FileRead.onload = function (e) {
if (FileRead.readyState === 2) {
AllTxtdata = FileRead;
var lines = FileRead.result.split('\n').map(function (line) {
return line.trim();
});
var select = $("select[name=MySelect]");
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function (line) {
if (line.endsWith(" -")) {
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
select.append("<optgroup id'" + currentGroup + "' label='" + currentGroup + "'>");
} else if (line === "") {
select.append("</optgroup>");
} else {
select.append("<option type='checkbox' id='" + (currentGroup + optionCounter) + "' name'"
+ (currentGroup + optionCounter) + "' value='"
+ line + "'>" + line + "</option>");
}
});
};
}
}
函数LoadTxtFile(p){
var AllTxtdata='';
var FileRead=new FileReader();
FileRead.onload=函数(e){
if(FileRead.readyState==2){
AllTxtdata=FileRead;
var lines=FileRead.result.split('\n').map(函数(行){
返回线.trim();
});
var select=$(“select[name=MySelect]”);
var optionCounter=0;
var currentGroup=“”;
行。forEach(函数(行){
if(第四行(“-”)){
currentGroup=line.substring(0,line.length-2);
optionCounter=0;
选择。追加(“”);
}else if(行==“”){
选择。追加(“”);
}否则{
select.append(“+line+”);
}
});
};
}
}
HTML
我试图用选项组和选项填充HTML下拉列表选择“MySelect” 您的代码中缺少一些东西
- 将事件附加到文件控件
- 从函数中读取实际文件
FileRead.readAsText(targetFile);
最后,在方法声明之外,将事件附加到文件控件
document.getElementById('myFile').addEventListener('change', LoadTxtFile, false);
在undefined中得到一个错误,表示行,有什么想法吗?行是foreach循环中使用的对象。它不能从外部访问。您是否在同一代码中遇到此错误??