繁体   English   中英

我如何摆脱这段代码中的重复项

[英]how can i get rid of duplication in this code

我的代码中有很多$(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');
  }



});

使用CSS类名称进行样式设置:

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

现在,不用设置.css()您可以使用:

addClass('selected')removeClass('selected')为橙色背景。

addClass('deselected')removeClasS('deselected')用于灰色背景。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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