简体   繁体   English

使用JavaScript从CSV文件创建并填充选择元素

[英]Create and populate select element from csv file using javascript

Having a bit of a problem looping through the csv file. 在csv文件中循环播放时出现问题。 I am also not sure if there isn't a simpler way of loading the text file. 我也不确定是否没有更简单的方式来加载文本文件。 I know a for each loop makes sense but I am not sure about the individual item in a csv file. 我知道for每个循环都有意义,但我不确定csv文件中的单个项目。 I want the whole line of text and I assign the two piece of text to the value and choice parts of the option. 我需要整个文本行,并将两段文本分配给选项的value和choice部分。 Any advice to clean this up? 有什么建议可以清理吗?

*UPDATE incorporating the suggestions below. *更新包含以下建议。 Error free but the created element is not being captured by my CSS file so the formatting is off and the select box only shows blanks. 没有错误,但是我的CSS文件未捕获所创建的元素,因此格式已关闭,并且选择框仅显示空白。

<script>
             function processCSV(file,parentNode)
             {
                var frag = document.createDocumentFragment()
                , lines = file.split('\n'), option;                 

                for (var i = 0, len = lines.length; i < len; i++){
                    option = document.createElement("option");
                    option.setAttribute("value", lines[i]);
                    option.innerHTML = lines[i];                        
                    frag.appendChild(option);
                    }
                plant_select.appendChild(frag);
             }

             var plant_select = document.createElement("select");  
             var intial_option = document.createElement("option");
             var datafile = '';
             var xmlhttp = new XMLHttpRequest();

             plant_select.setAttribute("class", "selectbox");   
             plant_select.setAttribute("id", "plant_select");
             intial_option.setAttribute("value","")
             intial_option.setAttribute("disabled","disabled")
             intial_option.setAttribute("selected","selected")
             intial_option.innerHTML = "Please select a Plant";
             plant_select.appendChild(intial_option)

             xmlhttp.open("GET","http://localhost:8080/res/plants.csv",true);
             xmlhttp.send();


             xmlhttp.onreadystatechange = function()
             {
                if(xmlhttp.status==200 && xmlhttp.readyState==4)
                {
                    processCSV(xmlhttp.responseText, plant_select);
                }
             }
        </script>

Supposing the display text is the first element, value as second in the CSV, and that you know your CSV is properly formatted. 假设显示文本是第一个元素,值在CSV中为第二个元素,并且您知道CSV的格式正确。

var dflines = datafile.split("\n");
for (var i=0; i<dflines.length; i++) {
    dflines[i] = dflines[i].split(",");
    plant_select.options[plant_select.options.length+1] = new Option(dflines[i][0],dflines[i][1],false,false);
}

Will add new select options to your current select. 将为您的当前选择添加新的选择选项。

There are a number of things you need to do here: 您需要在这里做很多事情:

  • You need to process your text correctly. 您需要正确处理文本。 Don't use for...in on strings or arrays. 请勿for...in字符串或数组上。 It isn't doing what you want it to do. 它没有按照您想要的去做。 Instead split the file into an array of lines and process these lines. 而是将文件拆分为行的数组并处理这些行。
  • In your processing loop, you are modifying the DOM on every single run. 在处理循环中,您在每次运行时都在修改DOM。 This causes reflows and repaints unnecessarily. 这会导致重排并不必要地重涂。 Instead, use a document fragment . 而是使用文档片段
  • You need your processing code in your callback, or preferably in a function called in your callback. 您需要在回调中或最好在回调中调用的函数中使用处理代码。

So your processing function: 所以你的处理功能:

    function processCSV(file,parentNode){
      var frag = document.createDocumentFragment()
        , lines = file.split('\n')
        , option
        ;
      for (var i = 0, len = lines.length; i < len; i++){
        option = document.createElement("option");
        option.setAttribute("value", "Choice"); 
        frag.appendChild(option);
      }
      parentNode.appendChild(frag);
    }

Then your XHR callback: 然后,您的XHR回调:

xmlhttp.onreadystatechange = function(){
  if(xmlhttp.status==200 && xmlhttp.readyState==4){
    processCSV(xmlhttp.responseText, plant_select);
  }
}

This doesn't do any per-line processing, but I'd need more information from you to be of any help there. 这不会按行进行任何处理,但是我需要您的更多信息以对您有所帮助。 You likely want to split by comma and look at individual data items, which you could do with a nested loop in the processCSV function. 您可能希望按逗号分割并查看各个数据项,这可以使用processCSV函数中的嵌套循环来processCSV

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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