javascript - 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)%>");
}
有没有更简洁的写法?
解决方案
你可以试试这个:
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 + ")%>");
推荐阅读
- javascript - 用函数创建方块并在 JavaScript 中移动带有 ID 的图片
- python - 我必须编写线性搜索,但我的代码似乎不起作用
- android - RTL 设备上的日期格式发生变化?
- sql-server - SSIS: Multiple Sources to 1 Destination
- c# - Adding of data to MySql database on remote server from C# desktop application
- vue.js - How do you access exported vm (main vue instance) object from a component?
- php - How to toggle mathematical operator and store calculations in a loop?
- python-3.x - How can you find when a value changes throughout every row in a data frame?
- javascript - 在多个节点之间转换单个节点的渐变填充
- python - Numpy:通过另一个数组组合数组列表(np.choose 替代)