如何根据输出值添加同一图像的“x”编号?

问题描述 投票:1回答:1

我对编码非常陌生,想知道如何根据输入和输出值多次插入相同的图像。我目前的基本添加代码是:

<form oninput="x.value=parseInt(a.value)+parseInt(b.value)">
  <input type="number" id="a" value="1"> +
  <input type="number" id="b" value="0"> =
  <output name="x" for="a b"></output>
</form>

现在,我希望能够添加与我获得的输出值相对应的多个图像。我怎样才能做到这一点?如果答案显而易见,我很抱歉。我对此很新。

javascript jquery html image
1个回答
0
投票

对于良好的实践,最好用function分隔HTML和Javascript。

您需要在该函数中执行这些步骤。

  1. 获取变量的输入值。
  2. 添加它们并使用document.getElementById().value显示
  3. 使用循环添加图像(c次)

这是工作代码

var update = () => {
  let a = parseInt(document.getElementById('a').value);
  let b = parseInt(document.getElementById('b').value);
  let c = isNaN(a + b) ? 0 : (a + b);
  document.getElementById('x').value = c;

  document.getElementById('images').innerHTML = '';
  for (let i = 0; i < c; i++) {
    document.getElementById('images').innerHTML += '<img src="http://via.placeholder.com/200x150">';
  }
}
<form oninput="update();">
  <input type="number" id="a" value="1"> +
  <input type="number" id="b" value="0"> =
  <output id="x" for="a b"></output>
</form>

<div id='images'></div>

用你的图像路径替换http://via.placeholder.com/200x150

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.