如何将输入变成事件监听器

时间:2019-10-17 11:44:31

标签: javascript input addeventlistener

我只想将下面的JavaScript代码转换为事件监听器:

function plot() {
  var f = document.querySelector("#function").value;
  var color = document.querySelector("#color").value;
  var derivative = document.querySelector("#der").value;

  parameters.data[0].fn = f;
  parameters.data[0].color = color;
  parameters.data[0].derivative.fn = derivative;

  functionPlot(parameters);
}

为澄清更多,查询:#der#color#function是html输入,我想使用addEventListener代替.value

谢谢

1 个答案:

答案 0 :(得分:1)

遍历每个选择器,向每个元素添加一个change侦听器,其中plot是侦听器:

['function', 'color', 'der'].forEach((id) => {
  document.getElementById(id).addEventListener('change', plot);
});

function plot() {
  var f = document.querySelector("#function").value;
  var color = document.querySelector("#color").value;
  var derivative = document.querySelector("#der").value;

  parameters.data[0].fn = f;
  parameters.data[0].color = color;
  parameters.data[0].derivative.fn = derivative;

  functionPlot(parameters);
}