0

我正在尝试根据用户想要购买的门票数量来获取和显示门票价格。当我运行我的代码时,它一开始完全符合我的要求,但是第二个数字覆盖了第一个,我如何将它们加在一起?

HTML:

     <ul id="tickets" class="clearfix registration-form"> 
            <li class="clearfix">
                <input type="hidden" id="ticket-price" value="90">
                <input class="short-input alpha number-tickets" type="number" placeholder="0" rel="#ticket-price">
                <label>Number of Tickets ($90 each)<p>This is some further information about tickets, and this can be as much information as you want it to be!</p></label>
            </li>
            <li class="clearfix">
                 <input type="hidden" id="ticket-price_2" value="35">
                 <input class="short-input alpha number-tickets" type="number" placeholder="0" rel="#ticket-price_2">
                 <label>Number of Tickets ($35 each)<p>This is some further information about tickets, and this can be as much information as you want it to be!</p></label>
            </li>
            <li class="tickets-total">
                 <label>Current Total = $</label>
                 <input id="ticketsTotal" type="number" placeholder="0.00" readonly="true">
            </li>
    </ul>

Javascript:

    $('input.number-tickets').keyup(function() {
    $('#tickets li input[type=number]')
            .not('#tickets li.tickets-total input[type=number]')
            .each(function(i, data) {
                var total = 0;
                var priceTotal = $(this).val() * $($(this).attr('rel')).val();

                for (var i=0; i < priceTotal.length; i++) {
                     total += priceTotal[i] << 0;
               }

               $('input#ticketsTotal').val(total);
    })
});

谢谢

4

3 回答 3

3

You need to declare the total variable (counter) outside of the $.each loop. As you have it now, you are setting the variable to 0 each time your loop runs.

var total = 0;
$('#tickets li input[type=number]')
    .not('#tickets li.tickets-total input[type=number]')
    .each(function (i, data) {
    var priceTotal = $(this).val() * $($(this).attr('rel')).val();

    for (var i = 0; i < priceTotal.length; i++) {
        total += priceTotal[i] << 0;
    }

    $('input#ticketsTotal').val(total);
});
于 2013-08-09T16:29:22.633 回答
2
$('input.number-tickets').keyup(function () {
    var total = 0;
    $('#tickets li input[type=number]')
        .not('#tickets li.tickets-total input[type=number]')
        .each(function (i, data) {
        var priceTotal = $(this).val() * $($(this).attr('rel')).val();

        for (var i = 0; i < priceTotal.length; i++) {
            total += priceTotal[i] << 0;
        }

        $('input#ticketsTotal').val(total);
    })
});
于 2013-08-09T16:29:42.667 回答
0

您应该使用旧值,例如

$('input#ticketsTotal').val(parseInt($('input#ticketsTotal').val()) + total);
于 2013-08-09T16:30:51.383 回答