html对象之options的增删改

如果,如果给一个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

 

来源:https://www.jb51.net/article/35205.htm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值