首页 > 解决方案 > 如何在函数之外使用变量?

问题描述

function ofInput() {
  const data = Array.from(
   this.children,
   tr => Array.from(tr.querySelectorAll('input'), input => input.value)
  );
}

document.querySelector('tbody').addEventListener('input', ofInput);

console.log(data);

该表在每个单元格中都有一个输入。将数据输出到输入时,数组中的数据应自动更改

标签: javascript

解决方案


The data variable is inside the scope of the function ofInput. You need to declare the variable outside of the scope of function to access it. Try this out:

let data;
function ofInput() {
  data = Array.from(
   this.children,
   tr => Array.from(tr.querySelectorAll('input'), input => input.value)
  );
}

document.querySelector('tbody').addEventListener('input', ofInput);

if (data && typeof(data) === "array") console.log(data);
else console.log("Event did not occur");


推荐阅读