本文介绍了javascript html选择动态添加optgroup和选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个< select id =chatsize =9/>
,我想添加一些optgroup和选项,这
var opt = {
friendchat:[
{name:somefriend1},
{name:somefriend2}
],
otherchat:[
{name:someother1},
{name:someother2}
],
friendrequest:[
{name:somerequest1},
{name:somerequest2}
],
sentrequest:[
{name:somesent1},
{name:somesent2}
]
};
$ b $(function(){
var $ select = $('#mySelect');
$ .each(opt,function(key,value){
$ var $ group $('< optgroup label =''+ key +'/>');
$ .each(value,function(){
$('< option / >').html(this.name).appendTo(group);
});
group.appendTo($ select);
});
});
let say i have a <select id="chat" size="9" />
, i want to add some optgroup and option which will be like this
with object like this
{friendchat:[{name:"somefriend1",...},{name:"somefriend2",...},
otherchat:[{name:"someother1",...},{name:"someother2",...},
friendrequest:[{name:"somerequest1",...},{name:"somerequest2",...},
sentrequest:[{name:"somesent1",...},{name:"somesent2",...}]
edit: typed input instead of select...
解决方案
Well, how about jQuery ?
var opt = {
friendchat:[
{name:"somefriend1"},
{name:"somefriend2"}
],
otherchat:[
{name:"someother1"},
{name:"someother2"}
],
friendrequest:[
{name:"somerequest1"},
{name:"somerequest2"}
],
sentrequest:[
{name:"somesent1"},
{name:"somesent2"}
]
};
$(function(){
var $select = $('#mySelect');
$.each(opt, function(key, value){
var group = $('<optgroup label="' + key + '" />');
$.each(value, function(){
$('<option />').html(this.name).appendTo(group);
});
group.appendTo($select);
});
});
这篇关于javascript html选择动态添加optgroup和选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!