简体   繁体   English

if 和 else 语句都在执行

[英]If and else both statement executing

I'm looping through all entries from database and using an if condition to check if the departmentID matches to my given ID.我正在遍历数据库中的所有条目并使用 if 条件来检查 departmentID 是否与我给定的 ID 匹配。 Problem is when the If condition is true it also runs the else condition but when the condition is false it only runs the else part which is fine.问题是当 If 条件为真时,它也会运行 else 条件,但当条件为假时,它只运行 else 部分,这很好。

$.ajax({
  url: "php/getall.php",
  type: 'GET',
  dataType: 'json',
  success: function(result) {
    employees = result['data'];
    console.log(employees);

    employees.forEach((employee) => {
      if (employee.departmentID === deptid) {
        $('#preventdel').modal('show');
      } else {
        $('#confirmdel').modal('show');
      }
    })
  }
})

It shows both modals if the condition is true but if the condition is not met it works fine如果条件为真,它会显示两种模态,但如果不满足条件,则它可以正常工作

If and else both executing want to exit the loop if the condition is met at once if 和 else 都在执行,如果条件立刻满足就想退出循环

You are executing your code inside a loop, so there should be as many modals as there are elements in the employee, because You are using if-else statement.您正在一个循环中执行代码,因此模式应该与员工中的元素一样多,因为您使用的是 if-else 语句。 So one of those two blocks of code will execute for each element.因此,这两个代码块之一将为每个元素执行。

const hasEmployee = employees.some(employee => employee.departmentID === deptid);
    
if (hasEmployee) {
  $('#preventdel').modal('show');
} else {
  $('#confirmdel').modal('show');
}

By using some() method, You can check if your searched elements exists in your results.通过使用some()方法,您可以检查搜索的元素是否存在于结果中。 Then open your modal only once at the end.然后最后只打开一次模态。

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

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