HTML选项框的设计以及根据不同选项的值对应不同的事件

文章目录

HTML选项框的设计

在前端页面的设计中,多选框的设计用select标签完成实现

  • 全部选项都显示的选项框
html 复制代码
<form>
	<select multiple="multiple">
			<option></option>
			<option>奥特曼</option>
			<option>奥特曼1</option>
			<option>奥特曼2</option>
	</select>
</form>

效果:

  • 展示只有一个块,选择通过下拉列表选择
html 复制代码
<select name="fruit">
  <option value="apple">苹果</option>
  <option value="banana">香蕉</option>
  <option value="orange">橙子</option>
</select>

效果图:

JS根据不同的选项框对应出不同的事件

  • 先找对select标签对应的元素
  • 再找到select标签被选中的索引
  • 然后根据索引和标签进行设置不同的事件
  • 简易流程:
html 复制代码
var mySelect = document.getElementById("testSelect");	//定位id(获取select)
var index = mySelect.selectedIndex;	//选中索引(选取select中option选中的第几个)
var text = mySelect.options[index].text;	//获取选中文本
var value = mySelect.options[index].value;	//获取选中值
mySelect.options[index].selected	//判断select中的某个option是否选中,true为选中,false为未选中

一个实际例子:

html 复制代码
<html>
<head>
    <script>
        function sel() {
            var mySelect = document.getElementById("testSelect");   //定位id(获取select)
            var index = mySelect.selectedIndex;   //选中索引(选取select中option选中的第几个)
			var text = mySelect.options[index].text; //获取选中文本,即option标签对之间的文字
            var value = mySelect.options[index].value;   //获取选中值
			document.getElementById("show_index").innerHTML = index;
			document.getElementById("show_text").innerHTML = text;
			document.getElementById("show_value").innerHTML = value;
			if (mySelect.options[2].selected) {  //注意index是从0开始的
				document.getElementById("show_isSelected").innerHTML = "选中了";
			} else {
				document.getElementById("show_isSelected").innerHTML = "没选中";
			}
        }
	</script>
</head>
<body>
    <select id="testSelect" onchange="sel()">
        <option id="op_1" value="Deep Learning">深度学习</option>
        <option id="op_2" value="Machine Learning">机器学习</option>
        <option id="op_3" value="Data Mining">数据挖掘</option>
        <option id="op_4" value="Image Processing">图像处理</option>
    </select>
    <br>
	<hr><font color="red">选中的option索引:</font><p id="show_index"></p>
	<hr><font color="red">选中的option文本:</font><p id="show_text"></p>
	<hr><font color="red">选中的option的值:</font><p id="show_value"></p>
	<hr><font color="red">"数据挖掘"选项是否被选中:</font><p id="show_isSelected"></p>
</body>
</html>

效果图:

参考文献: JavaScript和jQuery如何判断select是否被选中并获取select选中的值

相关推荐
Csvn6 小时前
OpenSpec 详细使用教程
前端
之歆7 小时前
Day19_LESS 完全指南——从入门到工程实践
前端·css·less
云水一下8 小时前
HTML5 从入门到精通:实战收官——从零搭建完整静态网站,综合运用所有知识
前端·html5
不总是8 小时前
Windows 系统 Node.js 免安装版(zip)安装与配置教程(2026 最新)
前端·windows·node.js
冬奇Lab8 小时前
每日一个开源项目(第105篇):Twenty - 跳出 Salesforce 的圈套,定义现代开源 CRM
前端·后端·开源
zhangyao9403309 小时前
开发pc端时,表格的高度怎么设置才能铺满页面
前端·javascript·elementui
kjs--10 小时前
浏览器书签执行脚本
前端
之歆10 小时前
Day16_JavaScript 轮播图与事件工程实战(下篇)
服务器·开发语言·前端·javascript·网络·性能优化
沄媪10 小时前
CSRF 跨站请求伪造
前端·ctf·csrf
kyriewen10 小时前
我关掉了Copilot:因为我写的代码出现在了别人的建议里
前端·javascript·ai编程