简体   繁体   中英

how can i get rid of duplication in this code

I have $(this).css() a lot in my code...im new to JS so I'm not sure what the best way to remove this duplication and make my code clean...

here is the link to my fiddle http://jsfiddle.net/d0okie0612/7Y2Qp/

  $(".btn-pvPanels").on('click', function(event) {
  var selected;
  selected = $(this).val();
  if(selected === "on-panel") {
  $(this).css({
    'background': 'orange', 
    'color': 'white'
  });
  $(this).parent().find('.btn-off').css({
    'background': '#F1F1F1', 
    'color': '#8E8D8D'
  });
  $('.aon_poff').fadeIn('slow');
  } 

else if(selected === "off-panel")  {
  $(this).css({
    'background': 'orange', 
    'color': 'white'
  });
  $(this).parent().find('.btn-on').css({
    'background': '#F1F1F1', 
    'color': '#8E8D8D'
  });
  $('.aon_poff').fadeOut('slow');
  }

else if(selected === "on-accessories")  {
  $(this).css({
    'background': 'orange', 
    'color': 'white'
  });
  $(this).parent().find('.btn-on').css({
    'background': '#F1F1F1', 
    'color': '#8E8D8D'
  });

  }

else if(selected === "on-accessories" && "on-panel")  {
  $(this).css({
    'background': 'orange', 
    'color': 'white'
  });
  $(this).parent().find('.btn-on').css({
    'background': '#F1F1F1', 
    'color': '#8E8D8D'
  });
     alert('hey')
  }

});


   $(".btn-accessories").on('click', function(event) {
var selected;
selected = $(this).val();
if(selected === "on-accessories") {
  $(this).css({
    'background': 'orange', 
    'color': 'white'
  });
  $(this).parent().find('.btn-off').css({
    'background': '#F1F1F1', 
    'color': '#8E8D8D'
  });
  $('.aoff_pon').fadeIn('slow');
  } 

else if(selected === "off-accessories")  {
  $(this).css({
    'background': 'orange', 
    'color': 'white'
  });
  $(this).parent().find('.btn-on').css({
    'background': '#F1F1F1', 
    'color': '#8E8D8D'
  });
  $('.aoff_pon').fadeOut('slow');
  }



});

Use CSS class names to style:

.selected { 
    background-color: orange;
    color: white;
}
.deselected {
    background-color: #F1F1F1;
    color: #8E8D8D;
}

Now instead of setting .css() you can use:

addClass('selected') and removeClass('selected') for the orange background.

addClass('deselected') and removeClasS('deselected') for the grey background.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM