写设计器的时候,总是需要对某些属性进行多选项的处理,总是用jquery处理,不能忘了本啊,写个纯JS的小例子复习一下。
这个小例子实现功能:
1.新增选项
2.删除选项
3.回显选项的Value和Text值
PS:回显信息功能只针对chrome和Firefox浏览器,IE浏览器请自觉转换监听方法
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>多选测试</title> <body> <div style="text-align:center"> <label for="op">输入Value</label><input type="text" id="opValue" /> <label for="op">输入Text</label><input type="text" id="opText" /> <input value="重置" type="button" οnclick="reset()" /> <input value="新增" type="button" οnclick="addOp()" /> <input value="删除" type="button" οnclick="deleteOp()" /> </div> <div style="text-align:center;margin-left:-73px;"> <select id="msel" style="width:155px;" multiple="multiple"> <option value="1">a1</option> <option value="2">a2</option> <option value="3">a3</option> </select> </div> </body> <script> //新增option function addOp(){ var msel =document.getElementById('msel'); var opValue = document.getElementById('opValue').value; var opText = document.getElementById('opText').value; var op = "<option value='"+opValue+"'>"+opText+"</option>"; msel.innerHTML+=op; } //删除选中option function deleteOp(){ var msel =document.getElementById('msel'); var selLength = msel.options.length; for (var i=0;i<selLength;i++){ var current = msel.options[i]; if (current.selected){ msel.options.remove(i); } } } //重置输入框 function reset(){ document.getElementById('opValue').value=""; document.getElementById('opText').value=""; } //回显选中的option的Value和Text值 document.getElementById('msel').addEventListener('click',function(e){ var target = e.target; var tagName = target.tagName.toLowerCase(); if (tagName=='option'){ document.getElementById('opValue').value=target.value; document.getElementById('opText').value=target.text; } }) </script> </html>