选择的option id 是01或02或03 不是value
时间: 2024-04-15 14:32:14 浏览: 21
如果你想根据 option 元素的 id 属性来判断选中的选项,而不是根据 value 属性,你可以使用 `querySelectorAll` 方法来获取所有的 option 元素,并遍历它们来检查是否选中。
以下是一个示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>下拉选择框示例</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<select id="s01">
<option value="">请选择</option>
<option id="01">选项1</option>
<option id="02">选项2</option>
<option id="03">选项3</option>
</select>
<table id="t1">
<tr>
<td>行1</td>
</tr>
<tr>
<td>行2</td>
</tr>
<tr>
<td>行3</td>
</tr>
</table>
<table id="t2">
<tr>
<td>行4</td>
</tr>
<tr>
<td>行5</td>
</tr>
<tr>
<td>行6</td>
</tr>
</table>
<script>
var selectElement = document.getElementById('s01');
var table1Element = document.getElementById('t1');
var table2Element = document.getElementById('t2');
selectElement.addEventListener('change', function() {
var selectedOptionIds = ['01', '02', '03'];
var selectedOptions = selectElement.querySelectorAll('option:checked');
// 清除之前加亮的行
table1Element.classList.remove('highlight');
table2Element.classList.remove('highlight');
// 判断选中的选项是否在指定的选项id列表中
for (var i = 0; i < selectedOptions.length; i++) {
var optionId = selectedOptions[i].id;
if (selectedOptionIds.includes(optionId)) {
// 添加加亮效果
table1Element.classList.add('highlight');
table2Element.classList.add('highlight');
// 弹出消息提示
alert('已选中 ' + optionId);
break; // 只需要处理第一个满足条件的选项
}
}
});
</script>
</body>
</html>
```
在上述代码中,通过给下拉选择框绑定 `change` 事件,当选中值发生变化时,会触发事件处理函数。在事件处理函数中,首先获取所有选中的 option 元素,然后遍历这些选项并判断它们的 id 属性是否在指定的选项 id 列表中。如果是,给表格 t1 和 t2 添加一个类来实现加亮效果,并弹出消息提示。如果选中的选项不在指定的选项列表中,则移除加亮效果。
你可以根据实际情况修改代码中的 ID 和选项 id 来适应你的页面布局和需求。同时,你可以根据需要自定义加亮效果和消息提示的样式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)