简体   繁体   English

如何将使用 classList.contains() 作为条件的 if 语句转换为 switch 语句?

[英]How to turn if statement that use classList.contains() as condition to switch statement?

How can I turn the following if/else if statement into switch statement?如何将以下if/else if语句转换为switch语句? Is it possible to do so?有可能这样做吗?

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');
      }

A switch is really for matching exact matches.开关实际上是为了匹配精确匹配。 There are some bad practices where you can use true in the switch for the match.有一些不好的做法,你可以在比赛的开关中使用 true 。 If you are looking to clean up the code.如果您正在寻找清理代码。 You can easily use variables to pull out common stuff, still will be a lot of code.您可以轻松地使用变量来提取常见的东西,但仍然会是很多代码。

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');
}

Other option is using an object and loop其他选项是使用 object 和循环

 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>

You can do like this...你可以这样做...

let follow = {"follow-user":"subscribedUsers", "follow-hashtag":"subscribedHashtags", "follow-cat":"subscribedCategories"}
Object.keys(follow).forEach(e=>{
      if(event.target.classList.contains(e)){
        sendFollowRequest(event.target, follow[e]);
      }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM