用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下拉选项》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

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

The Dream Machine

The Dream Machine

M. Mitchell Waldrop / Penguin Books / 2002-8 / USD 16.00

While most people may not be familiar with the name J. C. R. Licklider, he was the guiding spirit behind the greatest revolution of the modern era. At a time when most computers were big, ponderous ma......一起来看看 《The Dream Machine》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

MD5 加密
MD5 加密

MD5 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具