鍍金池/ 問答/HTML/ jquery 這段簡化要怎麼寫?

jquery 這段簡化要怎麼寫?

$(".menu_her").click(function() {
  $(".menu_her_layout").slideToggle();
  if($(".menu_her").text().indexOf("right")==-1){
    $(".menu_her .material-icons").text('chevron_right');
  }else{
    $(".menu_her .material-icons").text('expand_more');
  }
});

$(".menu_service").click(function() {
  $(".menu_service_layout").slideToggle();
  if($(".menu_service").text().indexOf("right")==-1){
    $(".menu_service .material-icons").text('chevron_right');
  }else{
    $(".menu_service .material-icons").text('expand_more');
  }
});

$(".menu_terms").click(function() {
  $(".menu_terms_layout").slideToggle();
  if($(".menu_terms").text().indexOf("right")==-1){
    $(".menu_terms .material-icons").text('chevron_right');
  }else{
    $(".menu_terms .material-icons").text('expand_more');
  }
});

這個jquery腳本如果是各位大神,可以怎麼簡寫?

回答
編輯回答
生性

提取公共方法

$(".menu_her").click(function(){
    click("menu_her");
});

$(".menu_service").click(function(){
    click("menu_service");
});

function click(evt){
    $("."+evt).slideToggle();
  if($("."+evt).text().indexOf("right")==-1){
    $("."+evt+" .material-icons").text('chevron_right');
  }else{
    $("."+evt+" .material-icons").text('expand_more');
  }
};
2017年3月14日 04:31
編輯回答
艷骨

補充樓上樓的一個字符沒拼接:function click(evt){

$("."+evt+'_layout').slideToggle();

if($("."+evt).text().indexOf("right")==-1){

$("."+evt+" .material-icons").text('chevron_right');

}else{

$("."+evt+" .material-icons").text('expand_more');

}
};

2017年8月12日 06:16