首页 > 解决方案 > 在 html 页面的不同位置显示来自输入字段的文本

问题描述

我想要实现的是在输入字段中输入文本,并在提交时希望文本出现在 HTML 页面的不同位置。

示例:我有一个包含以下行的页面

红车-绿车-

车-

在输入字段中输入 TEXT 后,我希望将行更改为

redcar-TEXT greencar-TEXT Yellowcar
-
TEXT

这可能实现吗?如果您有示例代码,将非常受欢迎。

这对我有用

function myFunction()
{
var x;


var person=prompt("Please enter your text","text");

if (person!=null)
  {
  x="redcar-" + person + "";
    document.getElementById("demo").innerHTML=x;
  }
}
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>

但我无法让它适用于多行

标签: javascripthtmlinput

解决方案


您可以这样做,只需将您想要的所有“汽车”添加到cars数组中

function myFunction() {
  const person = prompt("Please enter your text","text");
  const cars = ['redcar-', 'yellowcar-'];

  if (person != null) {
    document.getElementById("demo").innerHTML = cars.map(c => c + person).join('<br>');
  }
}
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>


推荐阅读