fle*_*esh 290 jquery user-interface drop-down-menu
正如问题所说,如何使用jQuery向DropDownList添加新选项?
谢谢
nic*_*ckf 451
不使用任何额外的插件,
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
Run Code Online (Sandbox Code Playgroud)
如果您有很多选项,或者需要非常频繁地运行此代码,那么您应该考虑使用DocumentFragment而不是不必要地多次修改DOM.对于少数选项,我会说它不值得.
- - - - - - - - - - - - - - - - 添加 - - - - - - - - - --------------
DocumentFragment是速度增强的好选择,但document.createElement('option')由于IE6和IE7不支持,我们无法创建选项元素.
我们可以做的是,创建一个新的选择元素,然后附加所有选项.一旦循环完成,将其附加到实际的DOM对象.
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());
Run Code Online (Sandbox Code Playgroud)
这样我们只会修改DOM一次!
Phr*_*ogz 162
没有插件,如果不使用尽可能多的jQuery,这可以更容易,而不是更老的学校:
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
$.each(myOptions, function(val, text) {
$('#mySelect').append( new Option(text,val) );
});
Run Code Online (Sandbox Code Playgroud)
如果要指定选项a)是否为默认选择值,并且b)现在应该选择,则可以传入另外两个参数:
var defaultSelected = false;
var nowSelected = true;
$('#mySelect').append( new Option(text,val,defaultSelected,nowSelected) );
Run Code Online (Sandbox Code Playgroud)
cgr*_*eno 13
使用插件:jQuery Selection Box.你可以这样做:
var myOptions = {
"Value 1" : "Text 1",
"Value 2" : "Text 2",
"Value 3" : "Text 3"
}
$("#myselect2").addOption(myOptions, false);
Run Code Online (Sandbox Code Playgroud)
Har*_*Har 11
您可能希望先清除DropDown $('#DropDownQuality').empty();
我让MVC中的控制器返回一个只有一个项目的选择列表.
$('#DropDownQuality').append(
$('<option></option>').val(data[0].Value).html(data[0].Text));
Run Code Online (Sandbox Code Playgroud)
在开头添加项目到列表
$("#ddlList").prepend('<option selected="selected" value="0"> Select </option>');
Run Code Online (Sandbox Code Playgroud)
最后将项目添加到列表中
$('<option value="6">Java Script</option>').appendTo("#ddlList");
Run Code Online (Sandbox Code Playgroud)