我怎样才能摆脱这段代码中的重复

时间:2013-03-26 20:42:36

标签: javascript jquery

我的代码中有很多$(this).css()...我是JS的新手,所以我不知道删除这个重复并使我的代码清理的最佳方法是什么......

这是我的小提琴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');
  }



});

1 个答案:

答案 0 :(得分:4)

使用CSS类名称样式:

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

现在,您可以使用:{/ p>而不是设置.css() 橙色背景的

addClass('selected')removeClass('selected')

addClass('deselected')removeClasS('deselected')为灰色背景。