【问题标题】:Why doesn't my innerHTML method work to list things in my contact form?为什么我的 innerHTML 方法无法在我的联系表单中列出内容?
【发布时间】:2017-12-08 05:02:25
【问题描述】:

我正在制作一个程序,我想知道为什么我在我的 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>";
    }
}

【问题讨论】:

  • 我还应该指出,我正在使用这个 jQuery 使按钮调用第一个函数: $(document).ready(function(){ $("button").click(function () { getFormElements(); }); });

标签: javascript forms html-lists innerhtml


【解决方案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>';

【讨论】:

  • 感谢您的评论。看起来它仍在做同样的事情。查看您的代码,看起来所做的只是创建一个变量,并在每次迭代时为其赋予一个新值。看起来它在每次迭代中都在做同样的事情(覆盖)。
  • @JustinRoohparvar 不,这不是一回事。在我的版本中,我使用+= 而不是=。如果您在代码中将= 替换为+=,它将起作用。我只是在使用innerHTML 之前积累了html,所以我们不会使用很多次并造成开销。正如我在评论中指出的那样 += 至关重要。
  • 我刚刚使用了您的较短加入版本,并且有效。但是,现在它在屏幕上闪烁(列表中的正确数据),但它立即消失了。
  • @JustinRoohparvar 可能您正在其他地方使用innerHTML
  • 不,先生,这是唯一的地方。我提交的代码就是我所拥有的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
  • 2012-03-28
相关资源
最近更新 更多