首页 > 解决方案 > 添加条件以确定值是否应该增加

问题描述

我正在寻找使用 jQuery 为我的票务系统创造条件。我有我的代码,我可以根据票的数量增加或减少购物篮总数,但我想更进一步,并且必须满足条件才能添加带有弹出窗口的票,告诉你有问题

例如:您不能有儿童票没有成人票...或者您不能有超过 2 个看护人...等

我尝试在我的代码中添加额外的 if 语句来增加/减少票证总数,但我无法让条件工作

我尝试使用 switch 语句,但我真的没有 JS 的经验来正确执行它,但我觉得它可能是一种选择?

这是我的代码的简化片段:

  var totalPrice = 0;

  $($(".valueBtn")).on("click", function(e) {
  var currTicket = $(this).closest("li");
  var targetClass = e.target.className;
  var targetTicketType = $(this)
    .closest("li")
    .attr("data-type");
  var targetTicketPrice = $(this)
    .closest("li")
    .attr("data-price");

  //plus value
  if (targetClass.indexOf("plus") > 0) {
    var currAmount = $(currTicket)
      .find(".currentValue")
      .html();
    if (currAmount >= 0) {
      $(currTicket)
        .find(".currentValue")
        .html(
          parseInt(
            $(currTicket)
              .find(".currentValue")
              .html()
          ) + 1
        );
      totalPrice = totalPrice + parseFloat(targetTicketPrice);
    }
  }

  //minus value
  if (targetClass.indexOf("minus") > 0) {
    var currAmount = $(currTicket)
      .find(".currentValue")
      .html();
    if (currAmount > 0) {
      $(currTicket)
        .find(".currentValue")
        .html(
          parseInt(
            $(currTicket)
              .find(".currentValue")
              .html()
          ) - 1
        );
      totalPrice = totalPrice - parseFloat(targetTicketPrice);
    }
  }

  //update basket total
  $("#basket").html(parseFloat(totalPrice).toFixed(2));
});

你可以在这里看到它: https ://codepen.io/cheesycoder/pen/KLjWPM

我只是在寻找正确方向的推动力。

如果有人可以帮助我创造条件,不允许在没有成人票的情况下添加儿童票,也许我可以从那里解决我的其余条件。

标签: javascriptjqueryif-statementconditional-statements

解决方案


推荐阅读