我正在尝试以表格格式显示输入数据。我现在遇到的问题是显示表将显示最后输入的数据。
HTML:
<table>
<thead>
<tr>
<th>Name</th>
<th>Value 1</th>
<th>Value 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Topic1</td>
<td><input type="text" class="Value_One"/></td>
<td><input type="text" class="Value_Two"/></td>
</tr>
<tr>
<td>Topic2</td>
<td><input type="text" class=" Value_One"></td>
<td><input type="text" class=" Value_Two"></td>
</tr>
</tbody>
</table>
<br/>
<table>
<thead>
<tr>
<th>Name</th>
<th>Value 1 </th>
<th>Value 2</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name">Topic1 </td>
<td class="value_1"></td>
<td class="value_2"></td>
</tr>
<tr>
<td class="name">Topic2</td>
<td class="display_value_1"></td>
<td class="display_value_2"></td>
</tr>
</tbody>
</table>
jQuery:
$(document).ready(function() {
$('input.Value_One').on('keyup change', function() {
$('td.display_value_1').text($(this).val());
});
$('input.Value_Two').on('keyup change', function() {
$('td.display_value_2').text($(this).val());
});
});
前1: 输入表
Name Value 1 Value 2
Topic1 1 100
Topic2
结果显示表
Name Value 1 Value 2
Topic1 1 100
Topic2 1 100
前2: 输入表
Name Value 1 Value 2
Topic1 1 100
Topic2 2 200
结果显示表
Name Value 1 Value 2
Topic1 2 200
Topic2 2 200
期望的结果:
Name Value 1 Value 2
Topic1 1 100
Topic2 2 200
JSFiddle https://jsfiddle.net/bhfhd4yr/18/
最佳答案
为输入分配相同的类。使用该类选择所有输入 ($inputs
)。将相同的类分配给目标单元格。使用该类选择所有目标单元格 ($values
)。每当触发输入的事件处理程序时,请使用 .index()
在 $inputs
中查找输入的索引。 。使用索引将当前输入值分配给$values
中相应的表格单元格:
var $inputs = $('.input');
var $values = $('.value');
$inputs.on('keyup change', function() {
var $this = $(this);
var idx = $inputs.index($this);
var value = $this.val();
$values.eq(idx).text(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Name</th>
<th>Value 1</th>
<th>Value 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Topic1</td>
<td>
<input type="text" class="input" />
</td>
<td>
<input type="text" class="input" />
</td>
</tr>
<tr>
<td>Topic2</td>
<td>
<input type="text" class="input">
</td>
<td>
<input type="text" class="input">
</td>
</tr>
</tbody>
</table>
<br/>
<table>
<thead>
<tr>
<th>Name</th>
<th>Value 1</th>
<th>Value 2</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name">Topic1</td>
<td class="value"></td>
<td class="value"></td>
</tr>
<tr>
<td class="name">Topic2</td>
<td class="value"></td>
<td class="value"></td>
</tr>
</tbody>
</table>
关于javascript - 以表格格式显示输入字段中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41496236/