首页 > 解决方案 > 每个循环不显示与控制台日志相同的结果

问题描述

我正在尝试显示输入<input>字段的结果。

这是我的代码:

$(document).ready(function(){

    $("#btn_copy").click(function(){
        $("input").each(function () {
            $("#final").html($(this).val());
            console.log($(this).val());
         });
    });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="excel_table">
      <thead>
          <tr>
            <th>Excel Data</th>
          </tr>
      </thead>
      <tbody>
          <tr>
            <td><input type="text"></td>
          </tr>
          <tr>
            <td><input type="text"></td>
          </tr>
          <tr>
            <td><input type="text"></td>
          </tr>
          <tr>
            <td><input type="text"></td>
          </tr>
          <tr>
            <td><input type="text"></td>
          </tr>
      </tbody>
    </table>

    <button id="btn_copy">Copy Over</button>

    <div id="final"></div>

控制台日志显示我想要的结果,当我尝试显示它时,它只显示最后一个输入字段。

有人可以指出我如何尝试显示所有结果的正确方向,就像控制台日志的方式一样吗?

另外,有人可以让我知道为什么它可以在控制台上运行,但不能在 html 上运行吗?

ps:片段隐藏显示,所以请展开片段使其全屏。

标签: jquery

解决方案


这是因为您没有将每个新输入值添加到#final。每次循环迭代都会覆盖它。尝试这样的事情:

  $(document).ready(function(){

    $("#btn_copy").click(function(){
        $("input").each(function () {
            $("#final").html($("#final").html() + $(this).val());
            console.log($(this).val());
         });
    });
  });

推荐阅读