jquery - 每个循环不显示与控制台日志相同的结果
问题描述
我正在尝试显示输入<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:片段隐藏显示,所以请展开片段使其全屏。
解决方案
这是因为您没有将每个新输入值添加到#final。每次循环迭代都会覆盖它。尝试这样的事情:
$(document).ready(function(){
$("#btn_copy").click(function(){
$("input").each(function () {
$("#final").html($("#final").html() + $(this).val());
console.log($(this).val());
});
});
});
推荐阅读
- vue.js - 如何在 vue.js 中用作插槽
- git - 当有新文件时运行 `git difftool --tool=vimdiff` 时,如何防止“/dev/null”出现?
- powershell - 使用 System.Management.Automation 和导出的会话,如何为 O365 调用指定凭据?
- flutter - 如何使用 GridView --Flutter 从服务器放置 JSON 数据
- c++ - 我可以在模板参数中使用指针吗?
- java - 在多节点 Spark 集群上运行时 Dataframe.collectAsList 方法的 Spark 问题
- lua - 尝试索引全局“消息”(一个零值)Lua 消息脚本
- sql - 在不同的数据库服务器中运行相同的查询但结果不同
- javascript - 注册为回调的命名箭头函数的正确语法是什么?
- django - 如何在 Django admin 中显示实际的外键 ID?