首页 > 解决方案 > Javascript - 检查是否为空的 if 语句不起作用

问题描述

我有一个看起来像这样的 javascript 函数

 Component comp = db.Components.Find(Model.ComponentID);
 Item i = db.Items.Find(Model.ItemID);

<script type="text/javascript">
 function clicked(e) {

            var compQty = $('#compQTY').val();
            var compQty = $('#compQTY').val();
            var compDiff = @Model.comp_qty - compQty;
            var compFuture = @comp.FSTK - compDiff;
            alert('compDiff = ' + compDiff )
                      if (!confirm('Are you sure? Doing this will reduce component ' + @comp.ComponentID + ' future stock from ' + @comp.FSTK+ ' to ' + compFuture))e.preventDefault();

                  if(@comp != null && @i == null) {
                      var compQty = $('#compQTY').val();
                      var compDiff = @Model.comp_qty - compQty;
                      var compFuture = @comp.FSTK - compDiff;
                      if (!confirm('Are you sure? Doing this will reduce component ' + @comp.ComponentID + ' future stock to ' + compFuture)) e.preventDefault();
                  }
                  else if(@i !== null && @comp == null ) {
                      var itemQty = $('#itemQTY').val();
                      var itemDiff = @Model.item_qty - itemQty;
                      var itemFuture = @i.FSTK - itemDiff;
                      if (!confirm('Are you sure? Doing this will reduce item ' + @i.ItemID + ' future stock to ' + itemFuture))e.preventDefault();
                  }
                  else if(@i !== null && @comp !== null) {
                      var itemQty = $('#itemQTY').val();
                      var itemDiff = @Model.item_qty - itemQty;
                      var itemFuture = @i.FSTK - itemDiff;
                      var compQty = $('#compQTY').val();
                      var compDiff = @Model.comp_qty - compQty;
                      var compFuture = @comp.FSTK - compDiff;

                      if (!confirm('Are you sure? Doing this will reduce component' + @comp.ComponentID + ' future stock to ' + compFuture + 'and reduce item' + @i.ItemID + ' future stock to ' + itemFuture))e.preventDefault();
                  }
              }
</script>

但例如在我的情况下,'i' 为空。所以没有满足 else if 语句,但它仍然给我一个错误 'i is null'。我已经尝试过@i != null@i !== null但它在这两种情况下都会出现错误

该功能还给我页面加载错误。当我的按钮被点击时,它应该只通过那个功能

标签: javascriptjquery

解决方案


推荐阅读