且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 jQuery 向 DropDownList 添加选项?

更新时间:2023-12-06 13:12:28

无需使用任何额外插件,

Without using any extra plugins,

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
    mySelect.append(
        $('<option></option>').val(val).html(text)
    );
});

如果您有很多选择,或者此代码需要非常频繁地运行,那么您应该考虑使用 DocumentFragment 而不是多次不必要地修改 DOM.对于少数选项,我会说这不值得.

If you had lots of options, or this code needed to be run very frequently, then you should look into using a DocumentFragment instead of modifying the DOM many times unnecessarily. For only a handful of options, I'd say it's not worth it though.

------------------------------- 已添加 --------------------------------

------------------------------- Added --------------------------------

DocumentFragment 是提高速度的好选择,但我们不能使用 document.createElement('option') 创建选项元素,因为 IE6 和 IE7 不支持它.

DocumentFragment is good option for speed enhancement, but we cannot create option element using document.createElement('option') since IE6 and IE7 are not supporting it.

我们可以做的是,创建一个新的 select 元素,然后附加所有选项.循环完成后,将其附加到实际的 DOM 对象中.

What we can do is, create a new select element and then append all options. Once loop is finished, append it to actual DOM object.

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
var _select = $('<select>');
$.each(myOptions, function(val, text) {
    _select.append(
            $('<option></option>').val(val).html(text)
        );
});
$('#mySelect').append(_select.html());

这样我们只会修改一次 DOM!

This way we'll modify DOM for only one time!