javascript - 带有多个 || 的 If 语句和 && 不工作

标签 javascript jquery json

我的 if 语句无法正常工作。

我正在从 JSON 文件中提取项目,尝试按品牌显示项目并显示多个类别。

因此,如果商品类别为 5 或 6 并且商品品牌字母仅为“C”,我需要显示这些商品。但由于某种原因,这个 if 语句还显示了其他品牌字母。前任。 “B”、“F”项目也正在显示。

它似乎没有发挥应有的作用。我无法像使用它一样使用 || 吗?因为如果我删除其中一个项目类别编号,它会起作用,但我无法显示这两个类别。

          //display peppers function 
          function displayPeppers() {
              var categoryImage = '';
              $.each(product_data, function (i, item) {
                  //convert JSON strings to uppercase for comparison
                  var brandLetter = item.itemBrandLetter.toUpperCase();
                  var foodService = item.itemDeli.toUpperCase();

                  if(item.itemCategory == 5 || item.itemCategory == 6 && brandLetter == "C" && foodService == "N") {
                    categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">' + '<a href="#"' + 'class="showProduct"' + 'data-itemcountry="' + item.itemCountry + '"' + 'data-itemcategory="' + item.itemCategory + '"' + 'data-itempageurl="' + item.itemFullUPC + '"' + 'data-itemgmo="' + item.itemGMOFree + '"' + 'data-itembpa="' + item.itemBPAFree + '"' + 'data-itemgluten="' + item.itemGlutenFree + '"' + 'data-itemlowsodium="' + item.itemLowSodium + '"' + 'data-itemkosher="' + item.itemKosherSym + '"' + 'data-itemorganic="' + item.itemOrganic + '"' + 'data-itemimage="' + item.imageURL + '"' + 'data-itemname="' + item.itemName + '"' + 'data-itemoz="' + item.itemPackSize + '"' + 'data-itemdescription="' + item.itemDescription + '"' + 'data-itemupc="' + item.itemFullUPC + '">' + '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">' + '<h3>' + item.itemName + '</h3>' + '</a>' + '</div>';
                  }
              });
              $('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
              closeNav();
          }

最佳答案

这可能会因多种原因而中断。主要与 && 和 || 到底是什么有关。指向?

是吗:

if ( 
( item.itemCategory == 5 || item.itemCategory == 6 ) && 
( brandLetter == "C" && foodService == "N" ) ) {}

还是……

if ( 
item.itemCategory == 5 || 
( item.itemCategory == 6 && brandLetter == "C" && foodService == "N" ) ) {}

等等。

使用括号来阐明应该解决哪些条件。

关于javascript - 带有多个 || 的 If 语句和 && 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41857226/

相关文章:

android - 如何在 Android 应用程序中将 ArrayList<Complex Object> 编码为 json 并将其发布到 Java REST Web 服务?

javascript - setInterval 的页面安全性

jquery - 防止click事件影响父jquery

php - 使用 PHP 和 jSON 从 MySQL 获取 UIImage

django sweetpie 和跨域 json

jquery - JQuery.parseJSON 的无效 JSon 错误

javascript - 两个 jQuery 函数不能一起工作?

javascript - jQuery 相当于普通 JavaScript classList 的什么?

javascript - 有没有办法在没有实例的情况下获取 css 类的值?

jQuery Mobile 使用 AJAX 数据增长文本区域