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

查看所有标签

猜你喜欢:

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

Clean Architecture

Clean Architecture

Robert C. Martin / Prentice Hall / 2017-9-20 / USD 34.99

Practical Software Architecture Solutions from the Legendary Robert C. Martin (“Uncle Bob”) By applying universal rules of software architecture, you can dramatically improve developer producti......一起来看看 《Clean Architecture》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

SHA 加密
SHA 加密

SHA 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具