jQuery UI 4 buttons. Code repeated 4 times, Can we make it shorter
$('#elmLeft').button({
icons: {
primary: "ui-icon-triangle-1-w"
},
text: false
});
$('#elmRight').button({
icons: {
primary: "ui-icon-triangle-1-e"
},
text: false
});
$('#elmTop').button({
icons: {
primary: "ui-icon-triangle-1-n"
},
text: false
});
$('#elmBottom').button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: fa开发者_Go百科lse
});
function setButton($element, icon) {
$element.button({
icons: {
primary: icon
},
text: false
});
}
setButton($('#elmLeft'), "ui-icon-triangle-1-w");
setButton($('#elmRight'), "ui-icon-triangle-1-e");
setButton($('#elmTop'), "ui-icon-triangle-1-n");
setButton($('#elmBottom'), "ui-icon-triangle-1-s");
Alternatively you could just take the selector instead of a jQuery element, and only the last letter of the string, but that seems like overkill.
You could put the icon differences in an object and use that to alter primary
:
var icons = {
elmLeft: 'w',
elmRight: 'e',
elmTop: 'n',
elmBottom: 's'
};
$('#elmLeft, #elmRight, #elmTop, #elmBottom').each(function() {
$(this).button({
icons: { primary: 'ui-icon-triangle-1-' + icons[this.id] },
text: false
});
});
I don't know if you'd consider that DRY enough to warrant the extra complexity though. If you had a class on the buttons then you could make it cleaner with:
$('.some_class').each(function() {
// As above.
});
Or perhaps you could add a function to icons
to keep the id
and icon information together:
var icons = {
elmLeft: 'w',
elmRight: 'e',
elmTop: 'n',
elmBottom: 's',
button: function(id) {
$('#' + id').button({
icons: { primary: 'ui-icon-triangle-1-' + this[id] },
text: false
});
}
};
icons.button('elmLeft');
icons.button('elmRight');
icons.button('elmTop');
icons.button('elmBottom');
Or take it one step further:
var buttons = {
ids: {
elmLeft: 'w',
elmRight: 'e',
elmTop: 'n',
elmBottom: 's'
},
create: function() {
for(id in this.ids) {
if(this.ids.hasOwnProperty(id)) {
$('#' + id').button({
icons: { primary: 'ui-icon-triangle-1-' + this.ids[id] },
text: false
});
}
}
}
};
buttons.create();
You could do the above with a self-executing function if you wanted a cleaner namespace:
(function() {
var ids = {
elmLeft: 'w',
elmRight: 'e',
elmTop: 'n',
elmBottom: 's'
};
for(id in ids) {
if(ids.hasOwnProperty(id)) {
$('#' + id').button({
icons: { primary: 'ui-icon-triangle-1-' + ids[id] },
text: false
});
}
}
})();
I'm sure it could be made shorter, but not in an elegant way as far as i can see, and the brevity would come at a cost of understandability.
精彩评论