用JavaScript往select元素中添加new option下拉选项

栏目: JavaScript · 发布时间: 7年前

内容简介:新建option对象,appendChild使用options的add方法:jQuery更简洁的写法:

方法一:用原生JavaScript创建

新建option对象,appendChild

select = document.getElementById('selectElementId');
var opt = document.createElement('option');
opt.value = value;
opt.innerHTML = innerHTML;
select.appendChild(opt);

使用options的add方法:

var obj=document.getElementById("select1");
obj.options.add(new Option(text,value));

方法二:jquery添加

$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
                    .attr("value",key)
                    .text(value)); 
});

jQuery更简洁的写法:

$('#mySelect').append($("<option/>", {
    value: key,
    text: value
}));

以上所述就是小编给大家介绍的《用JavaScript往select元素中添加new option下拉选项》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Rapid Web Applications with TurboGears

Rapid Web Applications with TurboGears

Mark Ramm、Kevin Dangoor、Gigi Sayfan / Prentice Hall PTR / 2006-11-07 / USD 44.99

"Dear PHP, It's over between us. You can keep the kitchen sink, but I want my MVC. With TurboGears, I was able to shed the most heinous FileMaker Pro legacy 'solu-tion' imaginable. It has relationshi......一起来看看 《Rapid Web Applications with TurboGears》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码