如果某个条件为真,如何更改动态创建元素的颜色?

时间:2017-10-12 15:19:32

标签: javascript

我创建了一些动态产品。我想要的是,如果产品数量减少到例如3然后变成橙色或者只剩下一个然后变成红色。 以下是管理员视图的动态产品的javascript:

function showProductAdmin() {

      lblProductList.innerHTML = "";

      for ( var i = 0; i < ajProductDataFromServer.length; i++ ) {

          var lblProduct = '<div class="lblProduct">' + '<img src="' + ajProductDataFromServer[i].image + '"width="85%" alt="product" class="lblProductImage" data-productImage="' + ajProductDataFromServer[i].image + '">' + '<h3 class ="lblProductName" data-productName="' + ajProductDataFromServer[i].name + '" >' + ajProductDataFromServer[i].name + '</h3>' + '<h3 class ="lblProductPrice" data-productPrice="' + ajProductDataFromServer[i].price + '">' + 'Price:' + ' ' + ajProductDataFromServer[i].price + '<h3 class ="lblProductQuantity" data-productQuantity="' + ajProductDataFromServer[i].quantity + '">' + 'Quantity:' + ' ' + ajProductDataFromServer[i].quantity + '</h3>' + '<button id="btnEditProductBody" class="btnShowPage btnEditProduct" data-showThisPage="pageUpdateProduct" data-productId="' + ajProductDataFromServer[i].id + '">' + 'EDIT PRODUCT' + '</button>' + '<button class="btnDeleteProduct" data-productId="' + ajProductDataFromServer[i].id + '" >' + 'DELETE PRODUCT' + '</button>' + '<h3 class="lblErrorMessage" id="lblDeleteProductErrorMessage">' + '</h3>' + '</div>';

          lblProductList.insertAdjacentHTML( 'beforeend', lblProduct );
          showPages();

      }


  }

然后是用户视图:

function showProduct() {

      lblProductList.innerHTML = "";

      for ( var i = 0; i < ajProductDataFromServer.length; i++ ) {

          var lblProduct = '<div class ="lblProduct">' + '<img src="' + ajProductDataFromServer[i].image + '" width="85%" alt="product">' + '<h3 class ="lblProductName">' + ajProductDataFromServer[i].name + '</h3>' + '<h3 class ="lblProductPrice">' + 'Price:' + ' ' + ajProductDataFromServer[i].price + '<h3 class ="lblProductQuantity">' + 'Quantity:' + ' ' + ajProductDataFromServer[i].quantity + '</h3>' + '<button class="btnBuyProduct" data-productId="' + ajProductDataFromServer[i].id + '" >' + 'BUY PRODUCT' + '</button>' + '</div>';

          lblProductList.insertAdjacentHTML( 'beforeend', lblProduct );
      }

  }

此处还有btnBuyProduct点击事件:

// BUY product for user
  document.addEventListener( "click", function(e) {

      if ( e.target.classList.contains( "btnBuyProduct" ) ) {

          sProductId = e.target.getAttribute( "data-productId" );
          console.log( sProductId );
          var sUrl = "api_buy_product.php?id=" + sProductId;

          var request = new XMLHttpRequest();
          request.onreadystatechange = function() {
              if ( this.readyState == 4 && this.status == 200 ) {

                  ajProductDataFromServer = JSON.parse( this.responseText );
                  console.log( "Response:" + ajProductDataFromServer );

                  if ( ajProductDataFromServer.buy == "ok" ) {

                      if ( !window.Notification ) {

                          alert( "Sorry, Notification Not supported in this Browser!" );

                      } else {

                          if ( Notification.permission === 'granted' ) {

                              notify = new Notification( 'SHOPAHOLIC.com', {
                                  body: 'The product has been added to your shopping cart!"', // the name of the pruduct
                                  icon: 'img_webshop/Fashion-Logo-6.png' // I could show the respective product image
                              });
                          }
                      }


                      playSound();

                      getajProductData();

                      //console.log( ajProductDataFromServer.quantity );
                      console.log( "PRODUCT QUANTITY DECREASED IN THE DATABASE" );

                  } else {

                      console.log( "PRODUCT QUANTITY DID NOT DECREASE IN THE DATABASE" );
                      lblDeleteProductErrorMessage.innerHTML = "";
                      var sDeleteProductErrorMessage = "Deleting Product Failed - Try again";
                      lblDeleteProductErrorMessage.insertAdjacentHTML( 'beforeend', sDeleteProductErrorMessage );

                  }
              }
          }

          request.open( "GET", "api_buy_product.php?id=" + sProductId, true );
          request.send();

      }

  });

为管理员和用户视图更新此颜色更改的最简单方法是什么?

1 个答案:

答案 0 :(得分:0)

在显示产品数量时,将数字包装到function dec2hex(str){ // .toString(16) only works up to 2^53 var dec = str.toString().split(''), sum = [], hex = [], i, s while(dec.length){ s = 1 * dec.shift() for(i = 0; s || i < sum.length; i++){ s += (sum[i] || 0) * 10 sum[i] = s % 16 s = (s - sum[i]) / 16 } } while(sum.length){ hex.push(sum.pop().toString(16)) } return hex.join('') } num = "76561198262006743" console.log("dec2Hex: " + dec2hex(num)) console.log("toString: " + parseInt(num).toString(16))元素中,并根据<span>,将匹配的类添加到包装ajProductDataFromServer[i].quantity中:

CSS:

<span>

span.orange { color: orange; } span.red { color: red; } span.green { color: green }

1)在showProduct()之前,添加:

var lblProduct = ...

或更短的版本:

var className = '';

if(ajProductDataFromServer[i].quantity > 3) {
    className = 'green';
} else if(ajProductDataFromServer[i].quantity <= 1) {
    className = 'red';
} else {
    className = 'orange';
}

然后,替换这部分:

var q         = ajProductDataFromServer[i].quantity;
var className = q > 3 ? 'green' : q <= 1 ? 'red' : 'orange';

用这个:

'<h3 class ="lblProductQuantity">' + 
    'Quantity:' + ' ' + ajProductDataFromServer[i].quantity + 
'</h3>'