javascript - 从表内的下拉列表中获取选定的值
问题描述
现在,我可以从表内下拉列表中的事件 onchange 中获取选定的值,但它仅适用于表的第一行。如果我要更改其他行的值,它仍然会从第一行获取值。
这是我的代码:
<table class="sortable" border="1" id="table">
<thead>
<tr>
<th>Employee Serial</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr style="font-size:11px">
<td>@item.empSerial</td>
<td ALIGN="center">
<select onchange="getSelValue()" id="drpTechnical" class="testerDrop" style="height:20px; width:100px; text-align-last:center; cursor:pointer">
<option value=@item.technicalComp>@item.grade1</option>
<option value=@item.empSerial>0</option>
<option value=@item.empSerial>1</option>
<option value=@item.empSerial>2</option>
<option value=@item.empSerial>3</option>
<option value=@item.empSerial>4</option>
</select>
</td>
</tr>
}
</tbody>
</table>
以及读取所选值的简单脚本:
function getSelValue() {
alert(document.getElementById("drpTechnical").value)
}
解决方案
document.getElementById
始终只返回具有此 ID 的第一个元素,因为 ID 应该是唯一的。
您想要的是从已更改的元素中获取 id。所以你需要this
function getSelValue(this) {
alert(this.value)
}
你的桌子应该是这样的
<td ALIGN="center">
<select onchange="getSelValue(this)" id="drpTechnical" class="testerDrop" style="height:20px; width:100px; text-align-last:center; cursor:pointer">
<option value=@item.technicalComp>@item.grade1</option>
<option value=@item.empSerial>0</option>
<option value=@item.empSerial>1</option>
<option value=@item.empSerial>2</option>
<option value=@item.empSerial>3</option>
<option value=@item.empSerial>4</option>
</select>
</td>
推荐阅读
- tensorflow.js - tensorflowjs-converter:导入元图失败,请检查错误日志以获取更多信息
- angular - 同一组件Angular的多个独立实例
- java - 镜像二叉树
- php - filter_input(INPUT_SERVER,'DOCUMENT_ROOT'); 返回空
- cors - 清除 APM-form 的缓存
- java - 如果我使用 Query 在“Android”中有用户 ID 数组列表,如何从“Firestore”集合中获取特定的文档列表
- unit-testing - 使用 Typemock 和 CodeRush 时的未知分析器问题
- flutter - 我想创建一个带有列表视图的颤振应用程序
- facet - Drupal 8:如何将构面链接到自定义构面处理器模块
- javascript - 如何在网格元素中正确嵌入铯