在 innerHTML 中包含变量值,为输入 ID 和占位符创建 运行 索引
include variable value in innerHTML to create running index for input id's and placeholders
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" "Waypoint 3" 作为占位符,同样对于 id,我希望它们位于位置 1、位置 2、位置 3 等。感谢您的帮助。我已经看到其他相关问题建议 + 符号连接,但它似乎不适用于此应用程序。
你只是用错了引号:
node.innerHTML = "<input id='place" + j +"' placeholder='" + j + "' onFocus='geolocate()' type='text' />";
这将完美地连接字符串并相应地插入您的号码。
编辑
只是为了将来,es6 能够创建 "Template Strings" 尚未在所有浏览器中可用:
node.innerHTML = `<input id="place ${j}" placeholder="${j}" onFocus="geolocate()" type="text" />`;
我想你需要用 "s 来结束你的字符串:
node.innerHTML = "<input id='place" +j+ "' placeholder='" +j+ "' onFocus='geolocate()' type='text' />"
这不是您问题的答案,但您可以通过将 addplace
回调函数作为参数放入事件处理程序来稍微清理一下代码,如下所示:
document.getElementById('addplace').addEventListener('click', addplace)
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" "Waypoint 3" 作为占位符,同样对于 id,我希望它们位于位置 1、位置 2、位置 3 等。感谢您的帮助。我已经看到其他相关问题建议 + 符号连接,但它似乎不适用于此应用程序。
你只是用错了引号:
node.innerHTML = "<input id='place" + j +"' placeholder='" + j + "' onFocus='geolocate()' type='text' />";
这将完美地连接字符串并相应地插入您的号码。
编辑
只是为了将来,es6 能够创建 "Template Strings" 尚未在所有浏览器中可用:
node.innerHTML = `<input id="place ${j}" placeholder="${j}" onFocus="geolocate()" type="text" />`;
我想你需要用 "s 来结束你的字符串:
node.innerHTML = "<input id='place" +j+ "' placeholder='" +j+ "' onFocus='geolocate()' type='text' />"
这不是您问题的答案,但您可以通过将 addplace
回调函数作为参数放入事件处理程序来稍微清理一下代码,如下所示:
document.getElementById('addplace').addEventListener('click', addplace)