我正在制作一个节目,我想知道为什么我在html页面上看到的只是表格,但只有一个。无序列表的项目符号列表应该在哪里。我在字段中输入了用户输入,但是当我点击提交时,它并没有显示字段中的数据,就像它应该的那样。这是代码。
function getFormElements() {
var gather_form_elements = new Array(
$("#first_name").val(),
$("#last_name").val(),
$("email").val(),
$("#phone_number").val()
);
displayValues(gather_form_elements);
}
function displayValues(gather_form_elements) {
for(i=0; i<gather_form_elements.length; i++)
{
document.getElementById("contact_info").innerHTML = "<li>" + gather_form_elements[i] + "</li>";
}
}
答案 0 :(得分:1)
因为你在每次迭代时都会覆盖它。在使用innerHTML
之前尝试累积html:
var html = "";
for(var i = 0; i < gather_form_elements.length; i++) {
html += "<li>" + gather_form_elements[i] + "</li>";
// ^^ the += is crucial. If you don't use it, it will just replace the content of html (the innerHTML in your code), we need to use += to append to html instead of overriding it.
}
document.getElementById("contact_info").innerHTML = html;
只使用一行代码就可以获得相同的结果:
document.getElementById("contact_info").innerHTML =
'<li>' + gather_form_elements.join('</li><li>') + '</li>';