如果,如果给一个select增加option你会怎么办?
大部分人会通过getElementById获取到select这个dom,然后通过append方法增加"<option>XXX<option>"这样的方式。
那么有没有更简单的直接操作dom的方法呢?有!
var obj=document.getElementById('element');
var index =obj.selectedIndex//选中的option的索引值
var text = obj[index]//选中的option的值
obj.options.remove(index)//删除索引index的option
obj.options.length=0//删除所有option
var val = obj.options[index].value//获取选中option的value
var text= obj.options[index].text//获取选中option的text
obj.options[index]=new Option(option中的文本text,option的value值);//修改option
obj.options.add(new Option(option中的文本text,option的value值)); //新增一个option
可以看出,写原生的时候,直接通过dom操作有时候会比其他方式更简单!
推荐大家多看看基础知识:
http://www.xiaoushuo.com/jsref/dom-obj-select.html http://www.xiaoushuo.com/jsref/dom-obj-option.html
或者
https://www.runoob.com/jsref/dom-obj-option.html https://www.runoob.com/jsref/dom-obj-select.html
或者
https://www.w3school.com.cn/jsref/dom_obj_select.asp https://www.w3school.com.cn/jsref/dom_obj_option.asp