优化(缩短)此代码块的最佳方法是什么?我正在使用Jquery UI插件“选择菜单”来分配选定数量的元素。
$('footer#footer form select').selectmenu({
style: 'dropdown',
appendTo: 'footer#footer form span'
});
$('form.filters section.grid .industry select').selectmenu({
style: 'dropdown',
appendTo: 'form.filters section.grid .industry'
});
$('form.filters section.grid .subject select').selectmenu({
style: 'dropdown',
appendTo: 'form.filters section.grid .subject'
});
$('form.filters section.grid .year select').selectmenu({
style: 'dropdown',
appendTo: 'form.filters section.grid .year'
});
$('form.filters section.grid .organiser select').selectmenu({
style: 'dropdown',
appendTo: 'form.filters section.grid .organiser'
});
答案 0 :(得分:2)
使用类和[data-*]
属性将数据传递给jQuery:
$('select.selectMenu').each(function () {
$(this).selectmenu({
style: 'dropdown',
appendTo: $(this).data('target')
});
});
这依赖于更改标记,以便select元素具有正确的类,并将[data-target]
属性设置为适当的值。
<select class="selectMenu" data-target="footer#footer form span">
...options...
</select>
each
正文和HTML的几个变体:
data
对象:$(this).selectmenu($(this).data());
<select data-style="dropdown" data-append-to="footer#footer form span">
[data-*]
属性:$(this).selectmenu($(this).data('selectmenu'));
<select data-selectmenu='{"style":"dropdown","appendTo":"footer#footer form span"}'>
答案 1 :(得分:1)
您可以将“选择器”地图添加到“追加”部分
var parts = {
'footer#footer form select' : ' span',
'form.filters section.grid .industry select' : '',
'form.filters section.grid .subject select' : '',
'form.filters section.grid .year select' : '',
'form.filters section.grid .organiser select': ''
};
for (var p in parts) {
$(p).selectmenu({
style: 'dropdown',
appendTo: p.replace(" select", parts[p])
});
}
或者你可以这样做。
$('footer#footer form select').selectmenu({
style: 'dropdown',
appendTo: 'footer#footer form select span'
});
$('form.filters section.grid .row * select').each(function() {
$(this).selectmenu({
style: 'dropdown',
appendTo: $(this).closest('.span3')
});
});