How to make this jquery code shorter?
Is there a way to make this code smaller into 1 block?
$('#product INPUT:checked').each(function () {
data.box1.push({
id: $(this).attr("id")
});
});
$('#product .dropSelect OPTION:selected').each(function () {
data.drops.pu开发者_开发百科sh({
value: $(this).val()
});
});
$('#product .setSelect OPTION:selected').each(function () {
data.set.push({
value: $(this).val()
});
});
Well, you can combine the second and third blocks easily using a test:
$('#product OPTION:selected').each(function () {
if ($(this).parent().hasClass("dropSelect")) {
data.drops.push({
value: $(this).val()
});
} else if ($(this).parent().hasClass("setSelect")) {
data.set.push({
value: $(this).val()
});
} // end if
});
While this isn't much shorter, it has the advantage of saving jQuery the trouble of selecting elements using classes, which is more intensive than selecting IDs or tags. By testing the existence of a class on a single element instead of on the entire document, you should improve your overall performance. (Granted it probably won't be a noticeable improvement, but optimization is rarely a bad thing.)
this shall work, note I prefer to use variables for readability and performance.
var $product = $('#product');
var selector = 'INPUT:checked, .dropSelect OPTION:selected, .setSelect OPTION:selected';
$(selector, $product).each( function () {
var $this = $(this);
if ( $this.is('INPUT:checked') ) data.box1.push( { id: this.id } );
if ( $this.hasClass('dropSelect') ) data.drops.push( { value: this.value } );
if ( $this.hasClass('setSelect') ) data.set.push( { value: this.value } );
});
You may not be able to make it shorter, but if you want it more modular you could try an approach like this:
function pushItems(items, dest, objFunc) {
items.each(function(i, el) { dest.push(objFunc(el)); });
}
function extractId(el) {
return { id: $(el).attr('id') };
}
function extractValue(el) {
return { value: $(el).val() };
}
pushItems($('#product INPUT:checked'), data.box1, extractId);
pushItems($('#product .dropSelect OPTION:selected'), data.drops, extractValue);
pushItems($('#product .setSelect OPTION:selected'), data.set, extractValue);
$('#product').each(function(){
$(this).children('input:checked').each(function(){
data.box1.push({
id: $(this).attr("id")
});
})
$(this).children('.dropSelect OPTION:selected').each(function(){
data.drops.push({
value: $(this).val()
});
})
$(this).children('.setSelect OPTION:selected').each(function(){
data.set.push({
value: $(this).val()
});
})
})
精彩评论