0

私のコードには$(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');
  }



});
4

1 に答える 1

4

CSSクラス名を使用してスタイルを設定します。

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

これで、設定の代わりに.css()次を使用できます。

addClass('selected')removeClass('selected')オレンジ色の背景。

addClass('deselected')灰色のremoveClasS('deselected')背景に。

于 2013-03-26T20:45:29.680 に答える