Posted in Javascript onJanuary 16, 2017
本文实例讲述了JavaScript实现的select点菜功能。分享给大家供大家参考,具体如下:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"> <title>点菜</title> <style type="text/css"> select{ width:120px; } </style> </head> <body> <select id="select1"> <option value="1">鸡蛋汤</option> <option value="2">海带汤</option> <option value="3">万峦猪脚</option> <option value="4">炸猪排</option> <option value="5">上海醉蟹</option> <option value="6">红烧狮子头</option> <option value="7">排骨炖白菜</option> </select> <input type="button" id="btnAdd" value="添加" /> <input type="button" id="btnClear" value="取消" /> <select id="select2"> </select> <input type="button" id="btnOk" value="确定" /> <script type="text/javascript"> //初始化 select 的 size 属性 var selectElement = document.getElementById("select1"); var select2Element = document.getElementById("select2"); var optionElements = selectElement.getElementsByTagName("option"); selectElement.size = optionElements.length; select2Element.size = optionElements.length; //获取添加按钮,并添加 click 事件 var btnAddElement = document.getElementById("btnAdd"); btnAddElement.onclick = function () { var selectElement = document.getElementById("select1"); if (selectElement.selectedIndex < 0) { alert("请选择菜单!"); return; } var select2Element = document.getElementById("select2"); var optionElements = selectElement.getElementsByTagName("option"); select2Element.appendChild(selectElement.options[selectElement.selectedIndex]); selectElement.removeChild(selectElement.options[selectElement.selectedIndex]); } //获取删除按钮,并添加 click 事件 var btnClearElement = document.getElementById("btnClear"); btnClearElement.onclick = function () { var selectElement = document.getElementById("select2"); if (selectElement.selectedIndex < 0) { alert("无可选菜单!"); return; } var select2Element = document.getElementById("select1"); var optionElements = selectElement.getElementsByTagName("option"); select2Element.appendChild(selectElement.options[selectElement.selectedIndex]); selectElement.removeChild(selectElement.options[selectElement.selectedIndex]); } //btnOk var btnClearElement = document.getElementById("btnOk"); btnOk.onclick = function () { var selectedElement = document.getElementById("select2"); var selectedElementLen = selectedElement.childNodes.length - 1; if (selectedElement.childNodes.length - 1 <= 0) { // } else { var caidan = ""; for (var i = 0; i < selectedElementLen; i++) { caidan = caidan + " " + selectedElement.options[i].text; } document.write("您选择的有:" + caidan); } } </script> </body> </html>
运行效果图如下:
希望本文所述对大家JavaScript程序设计有所帮助。
JavaScript实现的select点菜功能示例
- Author -
lx_3278@126声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@