在innerHTML中包含变量值以创建输入id's和占位符

include variable value in innerHTML to create running index for input id's and placeholders

本文关键字:占位符 id 输入 innerHTML 包含 变量值 创建      更新时间:2024-04-02

 document.getElementById('addplace').addEventListener('click', addplace);
j=1;
function addplace() {
  var node = document.createElement("li"); // Create a <li> node
  node.innerHTML = "<input id=''place'+j+' placeholder='+j+' onFocus='geolocate()' type='text' />"               
  document.getElementById("waypoints").appendChild(node);
  j++;
}
<ul id="waypoints"></ul>
<input id="addplace" type="submit"/>

我想要一个运行索引1、2、3等,而不是文本"+j+"作为占位符。我最终希望它像"Waypoint 1"、"Waypoint 2"answers"Waypoint 3"一样作为占位符,同样,对于id,我希望它们是位置1、位置2、位置3等。谢谢你的帮助。我看到其他相关的问题建议使用+符号进行连接,但它似乎不适用于此应用程序。

您只是使用了错误的引号:

node.innerHTML = "<input id='place" + j +"' placeholder='" + j + "' onFocus='geolocate()' type='text' />";

这将完美地连接字符串,并相应地插入您的数字。

编辑

只是为了将来,es6能够创建"模板字符串",这在每个浏览器中都是不可用的:

node.innerHTML = `<input id="place ${j}" placeholder="${j}" onFocus="geolocate()" type="text" />`;

我认为您需要put"s来结束您的字符串:

 node.innerHTML = "<input id='place" +j+ "' placeholder='" +j+ "' onFocus='geolocate()' type='text' />"

这不是问题的答案,但您可以通过将addplace回调函数作为参数放入事件处理程序中来稍微清理代码,如下所示:

document.getElementById('addplace').addEventListener('click', addplace)