首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何压缩多条jquery if语句

如何压缩多条jquery if语句
EN

Stack Overflow用户
提问于 2019-03-03 06:09:12
回答 1查看 27关注 0票数 0

虽然这很好用,但是最好的压缩方式是什么呢?

代码语言:javascript
复制
$('select').on('change', function() {
  var appointmenttypeval = $('#appointmenttype').val();
  if (appointmenttypeval == "") {
    document.getElementById("appointmenttype").setAttribute("class", "form-control");
  }
  if (appointmenttypeval == "urgent") {
    document.getElementById("appointmenttype").setAttribute("class", "p-3 mb-2 bg-danger text-white");
  }
  if (appointmenttypeval == "new") {
    document.getElementById("appointmenttype").setAttribute("class", "p-3 mb-2 bg-success text-white");
  }
  if (appointmenttypeval == "followup") {
    document.getElementById("appointmenttype").setAttribute("class", "p-3 mb-2 bg-warning text-dark");
  }
  if (appointmenttypeval == "labs") {
    document.getElementById("appointmenttype").setAttribute("class", "p-3 mb-2 bg-secondary text-white");
  }
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-03 06:16:19

使用从约会类型映射到类的对象。

代码语言:javascript
复制
const appointmentTypes = {
    "": "form-control",
    "urgent": "p-3 mb-2 bg-danger text-white",
    "new": "p-3 mb-2 bg-success text-white",
    "followup": "p-3 mb-2 bg-warning text-dark",
    "labs": "p-3 mb-2 bg-secondary text-white"
};
$("select").on("change", function() {
    var appointmenttypeval = $('#appointmenttype').val();
    if (appointmenttypeval in appointmentTypes) {
        $("#appointmenttype").attr("class", appointmentTypes[appointmenttypeval]);
    }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54963508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档