列出人口对其他功能选择的依赖性?

时间:2016-10-12 11:29:13

标签: javascript jquery

我有一个非常基本的小脚本,最多可选择3种产品,这将导致价格取决于夏季或冬季是否被选为季节。

我在这里做了一个小提琴: https://jsfiddle.net/Lantador/4chc7nkd/

我的问题是我想制作产品清单(productchoice),根据我选择的季节改变列出哪些产品(即2种不同的listes) - 但我不确定如何处理?

剧本:

$(function product() {
  var productchoice = {
    "No choice": "0",
    "Apples": "10.8",
    "Bananas": "17.2",
    "Cookies": "6.5",
    "Icecream": "10.8",
    "Lollipops": "6.5"
  };

  function populate(options) {
    var product_container = ""
    $.each(options, function(key, value) {
      product_container += '<option value="' + value + '">' + key + '</option>'
    });
    $(".product").each(function() {
      $(this).html(product_container);
      // this.innerHTML = container;
    });
  }

  $(".product").on("change", function() {
    var total = 0;
    $('.product').each(function() {
      total += parseFloat($(this).val());
    });
    $('.seasontype').each(function() {
      total *= parseFloat($(this).val());
    });
    $('#total').text(total.toFixed(2) + ' dollahbats');
  });

  populate(productchoice);
});




$(function seasontype() {
  var ktypevalg = {
    "Winter": "0.5",
    "Summer": "1.0",
  };

  function populate(options) {
    var ktype_container = ""
    $.each(options, function(key, value) {
      ktype_container += '<option value="' + value + '">' + key + '</option>'
    });
    $(".seasontype").each(function() {
      $(this).html(ktype_container);
      // this.innerHTML = container;
    });
  }

  $(".seasontype").on("change", function() {
    var total = 0;
    $('.fag').each(function() {
      total += parseFloat($(this).val());
    });
    $('.seasontype').each(function() {
      total *= parseFloat($(this).val());
    });
    $('#total').text(total.toFixed(2) + ' dollahbats');
  });

  populate(ktypevalg);
});

HTML:

  <center>
<br>3 options with different choices from a list:
<p>Choice 1:
    <select class="product" id="product1"></select>
</p>
<p>Choice 2:
    <select class="product" id="product2"></select>
</p>
<p>Choice 3:
    <select class="product" id="product3"></select>
</p>
<p>Total price: <span id="total">0.00 dollahbats</span>

</p>
<p>Season:
    <select class="seasontype" id="ktype1"></select>
</p>
    </center>

<br/>

1 个答案:

答案 0 :(得分:0)

您需要扩展您的产品列表:

var productchoice = {
    "No choice":
            {
                price: "0",
                winter: 1, //show in winter list
                summer: 1  //show in summer list
            }
    ,
    "Apples": {
        price: "10.8",
        winter: 0,  //do not show in winter list
        summer: 1   //show in summer list
    }
    //... and so on
};

然后在每次迭代中,您需要检查,季节是什么,并创建一个条件,该产品是否适用于该季节:

var product_container = '';
$.each(options, function (key, value) {
    if (($('#ktype1').val() == '0.5' && value.winter == 1) || ($('#ktype1').val() == '1.0' && value.summer == 1)) {
        product_container += '<option value="' + value.price + '">' + key + '</option>'
    }
});