我有以下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)%>");
}
是否有更简洁的书写方式?
答案 0 :(得分:0)
您可以节省多次创建同一jQuery对象的开销,只需创建一次,然后多次引用该对象即可。
var lnkObj = $('#follow_link_<%=@artist.id%>';
if (lnkObj.hasClass('btn-lg')) {
lnkObj.replaceWith("<%=j link_to_follow(@artist,'lg')%>");
} else if (lnkObj.hasClass('btn-sm')) {
lnkObj.replaceWith("<%=j link_to_follow(@artist,'sm')%>");
} else {
lnkObj.replaceWith("<%=j link_to_follow(@artist)%>");
}
答案 1 :(得分:0)
您可以尝试以下方法:
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 + ")%>");