javascript - 如何将使用 classList.contains() 作为条件的 if 语句转换为 switch 语句?
问题描述
如何将以下if/else if
语句变成switch
语句?有可能这样做吗?
if(event.target.classList.contains("follow-user")){
sendFollowRequest(event.target, 'subscribedUsers');
} else if(event.target.classList.contains("follow-hashtag")){
sendFollowRequest(event.target, 'subscribedHashtags');
} else if(event.target.classList.contains("follow-cat")){
sendFollowRequest(event.target, 'subscribedCategories');
}
解决方案
开关实际上是为了匹配精确匹配。有一些不好的做法,你可以在比赛的开关中使用 true 。如果您正在寻找清理代码。您可以轻松地使用变量来提取常见的东西,但仍然会是很多代码。
var target = event.target
var cList = target.classList
if(cList.contains("follow-user")){
sendFollowRequest(target, 'subscribedUsers');
} else if(cList.contains("follow-hashtag")){
sendFollowRequest(target, 'subscribedHashtags');
} else if(cList.contains("follow-cat")){
sendFollowRequest(target, 'subscribedCategories');
}
其他选项是使用对象和循环
var subscribedOptions = {
'follow-user': 'subscribedUsers',
'follow-hashtag': 'subscribedHashtags',
'follow-cat': 'subscribedCategories',
}
function clicky(event) {
var target = event.target;
var cList = target.classList;
Object.entries(subscribedOptions).forEach(function(req) {
if (cList.contains(req[0])){
sendFollowRequest(target, req[1]);
}
})
}
function sendFollowRequest(target, action) {
console.log(target, action);
}
document.querySelectorAll(".bar").forEach(b => b.addEventListener("click", clicky))
<button class="foo bar follow-hashtag">foo bar follow-hashtag</button>
<button class="foo bar follow-user">foo bar follow-user</button>
<button class="foo bar follow-cat">foo bar follow-cat</button>
推荐阅读
- c++ - 将 boost 函数与 boost 绑定与地图一起使用
- javascript - 如果所选选项的值动态更改,则选择标签值不会更新
- c# - 无法加载文件或程序集或其依赖项之一,错误消息正在更改
- apache-pulsar - 错误没有这样的文件或目录:_pulsar.so
- spring-boot - @ConditionalOnMissingBean 不能被覆盖
- android - 如何创建不同形状的浮动操作按钮
- firebase - Firebase Cloud Functions 调度程序位置
- python - 使用 PyWinAuto 返回所有桌面窗口
- ibm-mq - 是否可以将 MQ 与 Katalon 一起使用?
- spreadsheet - 通过 OnlyOffice API 更改电子表格单元格的格式