首页 > 解决方案 > jQuery:如何以简洁的方式编写 if hasClass 语句

问题描述

我有以下 if / else if / else 语句:

if ($('#follow_link_<%=@artist.id%>').hasClass('btn-lg')) {
  $('#follow_link_<%=@artist.id%>').replaceWith("<%=j link_to_follow(@artist,'lg')%>");
} else if ($('#follow_link_<%=@artist.id%>').hasClass('btn-sm')) {
  $('#follow_link_<%=@artist.id%>').replaceWith("<%=j link_to_follow(@artist,'sm')%>");
} else {
  $('#follow_link_<%=@artist.id%>').replaceWith("<%=j link_to_follow(@artist)%>");
}

有没有更简洁的写法?

标签: javascriptjquery

解决方案


你可以试试这个:

var checkFor = $('#follow_link_<%=@artist.id%>');
if(checkFor.hasClass('btn-lg')){
  newVal = ",'lg'";
} else if(checkFor.hasClass('btn-sm')){
  newVal = ",'sm'";
}
checkFor.replaceWith("<%=j link_to_follow(@artist" + newVal + ")%>");

推荐阅读