jQuery计算价格无效(正确)

时间:2014-05-12 17:10:55

标签: javascript jquery html shop

$(function() {

var base_price = 0;
CalculatePrice();

$(".math1").on('change', function(e) {
    CalculatePrice();
});


function CalculatePrice() {
    var base_cost = base_price;
    $('.math1').each(function() {
        base_cost += $(this).find('option:selected').data("price");
    });
    $("#price").text(base_cost.toFixed(2)*32);    
}


});

该脚本将查看所选选项的所有数据价格并执行此操作:

data-price (of select 1) + data-price (of select 2)

但它需要这样做:

data-price (of select 1) * data-price (of select 2)

它将返回一个标准值,例如:

2 person room = $32, 2 2 person rooms = $64 (correctly)
4 person room = $64, 2 4 person rooms = $96 (must be + 64 instead of 32 so will return $128)
6 persoon room = $128, 2 6 person rooms= $160 (must be +128 so will return $256)

小提琴:http://jsfiddle.net/5HkEh/3/

注意:这不起作用

base_cost *= $(this).find('option:selected').data("price");

2 个答案:

答案 0 :(得分:1)

设置base_price = 1

然后将您的+=更改为*=

答案 1 :(得分:0)

我认为根据您的逻辑,您需要将第二个选择控制器更改为此

<select class="twee math1 c2 level-3" name="roomcount" id="select-02">
    <option title="0b" data-price="0"></option>
    <option title="1b" data-price="1">1</option>
    <option title="2b" data-price="2">2</option>
    <option title="3b" data-price="3">3</option>
    <option title="4b" data-price="4">4</option>
</select>

$(".c2").each(function(index) {
    var y = $(this).find('option:selected').data("price");
    base_cost *= y;
});