这是我的代码
$('select.more-search').each(function(i, e){
more_srch[i] = $(this).attr('name');
$('#'+more_srch[i]+' :selected').each(function(j, selected){
more_sel[i][j] = $(selected).val();
});
});
在控制台显示错误为TypeError: more_sel[i] is undefined
如何消除这个错误?
需要先将more_sel[i]
初始化为空数组,然后才能对元素进行赋值。
$('select.more-search').each(function(i, e){
more_srch[i] = $(this).attr('name');
more_sel[i] = [];
$('#'+more_srch[i]+' :selected').each(function(j, selected){
more_sel[i][j] = $(selected).val();
});
});
不用.each()
,可以用.map()
:
$('select.more-search').each(function(i, e){
more_srch[i] = $(this).attr('name');
more_sel[i] = $('#'+more_srch[i]+' :selected').map(function(j, selected){
return $(selected).val();
}).get(); // use .get() to turn returned jQuery object into normal array
});