我有一张这样的表:
<table id="mytable">
<tr>
<th>Customer Id</th>
<th>Name</th>
</tr>
<tr>
<td>123</td>
<td>A</td>
</tr>
<tr>
<td>456</td>
<td>B</td>
</tr>
<tr>
<td>789</td>
<td>C</td>
</tr>
</table>
<form>
<input type="text" name="txtDsCode" id="txtDsCode"/>
</form>
当我点击textbox
然后点击表格中的cell
时,该单元格的值将显示在textbox
中。
我该怎么做javascript?
谢谢大家!
答案 0 :(得分:2)
querySelectorAll
选择td
元素Array.from
将array-like-object
投射到array
以应用array
方法addEventListener
var cells = document.querySelectorAll('#mytable td');
Array.from(cells).forEach(function(elem) {
elem.addEventListener('click', function() {
document.getElementById('txtDsCode').value = this.textContent;
})
})
<table id="mytable">
<tr>
<th>Customer Id</th>
<th>Name</th>
</tr>
<tr>
<td>123</td>
<td>A</td>
</tr>
<tr>
<td>456</td>
<td>B</td>
</tr>
<tr>
<td>789</td>
<td>C</td>
</tr>
</table>
<form>
<input type="text" name="txtDsCode" id="txtDsCode" />
</form>