如何压缩多个jquery if语句

时间:2019-03-02 22:09:12

标签: jquery

尽管这很好,但凝聚它的最佳方法是什么

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

1 个答案:

答案 0 :(得分:1)

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

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