【问题标题】:Multiply output by inputs输入乘以输出
【发布时间】:2022-08-24 22:37:56
【问题描述】:

我正在尝试根据 2 个输入字段创建一个列表。第一个输入将是一个名称,第二个输入是一个整数。

我试图实现的是将显示的名称乘以输入整数的数量。我已经根据输入获得了要显示的名称,但无法根据输入整数多次显示它。

这是我希望实现的示例图像

<html>
<head>
<style>
input {
    display: block;
}
#msgs {
    margin-bottom: 24px;
}
</style>
<meta charset=\"utf-8\">
<title>Test</title>
</head>

<body>
<input type=\"text\" value=\"Michael\" id=\"name\" />
<input type=\"text\" value=\"5\" id=\"count\" />
<input type=\"button\" value=\"add to list\" id=\"add\" />
<div id=\"list\"> </div>
</body>
<script>
    document.getElementById(\"add\").onclick = function() {
  var text = document.getElementById(\"name\").value; 
  var div = document.createElement(\"div\");
  div.textContent = text;
  document.getElementById(\"list\").appendChild(div);
  document.getElementById(\"name\").value = \"\"; // clear the value
}
</script>
</html>

小提琴:https://jsfiddle.net/grnct2yz/

  • 为什么不使用循环?
  • @KonradLinkowski Tbh,我对这些东西 atm 不太熟悉

标签: javascript html input


【解决方案1】:

<html>
<head>
<style>
input {
    display: block;
}
#msgs {
    margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>

<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
    document.getElementById("add").onclick = function() {
  var text = document.getElementById("name").value; 
  for(let i = 0; i < document.getElementById("count").value; i++) {
    var div = document.createElement("div");
    div.textContent = text;
    document.getElementById("list").appendChild(div);
  }
  document.getElementById("name").value = ""; // clear the value
}
</script>
</html>

我添加了一个循环并将输入类型更改为数字,因此我们确定它将在循环中插入一个数字。这是你想要的吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多