javascript 如何从使用createElement()创建的HTML输入(文本)中获取用户数据?

5jvtdoz2  于 2023-01-04  发布在  Java
关注(0)|答案(2)|浏览(228)

"我的问题"
我希望得到一些帮助,以了解如何访问input1和input2中的值,将它们存储在变量中,以便稍后可以将它们用于一个函数,该函数将计算这两个值并将其显示在结果div中。

const input1 = document.createElement("input");
document.body.appendChild(input1);

const input2 = document.createElement("input");
document.body.appendChild(input2);

const result = document.createElement("div");
document.body.appendChild(result);
k97glaaz

k97glaaz1#

一种方法是对创建的输入使用EventListener来操作数据

const input1 = document.createElement("INPUT");
document.body.appendChild(input1);
input1.addEventListener('change', function (e) {

  var target = e.target || e.srcElement;
  console.log(target.value);
});

你也可以添加一个选择器(id或class)到创建的元素,并通过这个选择器恢复它
x一个一个一个一个x一个一个二个x
你的样本看起来像
一个三个三个一个
如果你必须动态创建div和showresult,你也可以创建按钮并操作onclick事件

var numberOfRow = 0;

function copyResultInNextInput(nextNumber, result) {
  var next = document.getElementById('input1_' + (nextNumber));
  if (next) {
    next.value = result.innerText;
  }
}

function createNewRow(haveSeveralButtons) {
  numberOfRow++;
  const nextNumber = numberOfRow + 1;
  const input1 = document.createElement("INPUT");
  input1.id = 'input1_' + numberOfRow;
  document.body.appendChild(input1);

  const input2 = document.createElement("INPUT");
  input2.id = 'input2_' + numberOfRow;
  document.body.appendChild(input2);

  const result = document.createElement("DIV");
  result.id = 'result_' + numberOfRow;
  document.body.appendChild(result);

  const button = document.createElement("BUTTON");
  button.innerText = 'show result';
  button.addEventListener('click', function() {
    result.innerText = input1.value * input2.value;
    if (!haveSeveralButtons) {
      copyResultInNextInput(nextNumber, result);
    }
  });
  document.body.appendChild(button);

  if (haveSeveralButtons) {
    const button2 = document.createElement("BUTTON");
    button2.innerText = 'copy result in next input1';
    button2.addEventListener('click', function() {
      copyResultInNextInput(nextNumber, result);
    });
    document.body.appendChild(button2);
  }

  const hr = document.createElement("HR");
  document.body.appendChild(hr);
}
<button onclick="createNewRow(false)">create New Row with one button</button>
<button onclick="createNewRow(true)">create New Row with two buttons</button>
<hr/>
j7dteeu8

j7dteeu82#

好的,这样Id就可以工作了,但是它只对那一行有效。我需要在每一个新创建的行上独立地重复这个过程(等式)。

相关问题