如何使用jQuery向DropDownList添加选项? [英] How do I add options to a DropDownList using jQuery?
问题描述
谢谢
不使用任何额外的插件,
var myOptions = {
val1:'text1',
val2:'text2'
};
var mySelect = $('#mySelect');
$ .each(myOptions,function(val,text){
mySelect.append(
$('< option>< / option>')。val(val) (文字)
);
});
如果您有很多选项,或者该代码需要频繁运行,那么您应该看使用 DocumentFragment ,而不是不必要地修改DOM。只有少数选择,我会说这不值得。
------------------ -------------添加--------------------------------
DocumentFragment
是增强速度的好选择,但是我们无法使用 create.createElement('选项')
因为IE6和IE7不支持它。
我们可以做的是创建一个新的select元素,然后附加所有选项。一旦循环完成,将其附加到实际的DOM对象。
var myOptions = {
val1:'text1'
val2:'text2'
};
var _select = $('< select>');
$ .each(myOptions,function(val,text){
_select.append(
$('< option>< / option>')。val(val) (文字)
);
});
$('#mySelect')。append(_select.html());
这样我们将只修改DOM一次!
As the question says, how do I add a new option to a DropDownList using jQuery?
Thanks
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)
);
});
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
is good option for speed enhancement, but we cannot create option element using document.createElement('option')
since IE6 and IE7 are not supporting it.
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());
This way we'll modify DOM for only one time!
这篇关于如何使用jQuery向DropDownList添加选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!