【问题标题】:JavaScript how can I get the data outside " myForm.addEventListener"?JavaScript 如何获取“myForm.addEventListener”之外的数据?
【发布时间】:2021-12-30 05:40:42
【问题描述】:

我是新来的。我在github 上找到了一个很棒的 Skript。 我的问题:如何在“myForm.addEventListener”之外获取数据我试图将其声明为全局变量,但在我的情况下不起作用我希望你能阻止我。

    const myForm = document.getElementById("myForm");
    const csvFile = document.getElementById("csvFile");

    function csvToArray(str, delimiter = ",") {

      // slice from start of text to the first \n index
      // use split to create an array from string by delimiter
      const headers = str.slice(0, str.indexOf("\n")).split(delimiter);

      // slice from \n index + 1 to the end of the text
      // use split to create an array of each csv value row
      const rows = str.slice(str.indexOf("\n") + 1).split("\n");

      // Map the rows
      // split values from each row into an array
      // use headers.reduce to create an object
      // object properties derived from headers:values
      // the object passed as an element of the array
      const arr = rows.map(function (row) {
        const values = row.split(delimiter);
        const el = headers.reduce(function (object, header, index) {
          object[header] = values[index];
          return object;
        }, {});
        return el;
      });

      // return the array
      return arr;
    }

    myForm.addEventListener("submit", function (e) {
      e.preventDefault();
      const input = csvFile.files[0];
      const reader = new FileReader();

      reader.onload = function (e) {
        const text = e.target.result;
        const data = csvToArray(text);
        document.write(JSON.stringify(data));
      };
      
      reader.readAsText(input);
    });
<head> </head>
<body>
  <form id="myForm">
    <input type="file" id="csvFile" accept=".csv" />
    <br />
    <input type="submit" value="Submit" />
  </form>

</body>

【问题讨论】:

  • 声明一个函数,并从事件监听器中调用它。

标签: javascript callback addeventlistener


【解决方案1】:

您可以在任何地方构造FileReader 并定义其.onload 方法。您也可以在任何地方调用它的.readAsText 方法,但请注意那里的代码假设“csvFile”元素有一个类似数组的.files 属性,其中至少包含一个文件读书。 (另请注意,即使 .onload 在脚本中出现的时间比 .readAsText 早,但它直到之后才会被应用——这是浏览器知道 .readAsText 得到结果的方式。)

如果该假设在页面加载后立即成立,则您可以立即执行所有操作(例如在DOMContentLoaded 侦听器中)。另一方面,如果假设仅在用户完成某些表单字段后才有效,那么您不能比提交事件侦听器更早地阅读它。

您要对文件中的文本执行的任何操作都应该发生在阅读器的.onload 方法中,因为这是您的脚本首先可以使用文件内容的地方。现有代码创建了一个不错的行对象数组(绑定到data),然后大胆地用它覆盖整个网页(在将其编码为 JSON 字符串之后)。

您可能更愿意编写一个函数,该函数循环遍历每一行(对象)中的每一列(属性)并对值进行处理——对于初学者,您可以将每个键/值对打印到浏览器控制台,例如:

for (const thisRowObj of data){
  for (const thisKey in thisRowObj){
    const thisValue = thisRowObj[thisKey];
    console.log(`${thisKey}: ${thisValue}`);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 2022-08-17
    • 2021-11-21
    • 2018-12-05
    • 1970-01-01
    • 2018-05-21
    相关资源
    最近更新 更多