Why is this simple function not working

前端 未结 3 1297
刺人心
刺人心 2020-12-11 12:55

Why isn\'t this working? Similar code works here: http://www.ralphphillips.com/youtube/stick-figure/stick-figure2.html

But this isn\'t working. I have the html code

3条回答
  •  清歌不尽
    2020-12-11 13:21

    I would rewrite the checkOptions and checkAccomp functions and remove all these if statements using this pattern: create an object that stores the id of each checkbox and its corresponding price, and then use a for-in loop with key value lookup, like this:

    var OptionPricing = {     
    
        'pack11049': 1049,
        'pack21199': 1199,
        'pack31199': 1199,
        'pack41299': 1299,
        'pack61499': 1499
    };
    
    var AccompPricing = {
    
        0: 0,
        1: 129,
        2: 258,
        3: 1057,
        4: 1856 
    };
    
    function checkOptions() {
    
        var Price = 0;
    
        for (Packs in OptionPricing) {
    
            if ($('#' + Packs).is(':checked')) {           
                Price += OptionPricing[Packs];
            }
        }
    
        return Price;
    }
    
    function checkAccomp() {
    
        var Accomp = parseInt($('#HowMany').val(), 10);
    
        return AccompPricing[Accomp];
    }
    
    function updateTotal() {
    
        var ThePrice = checkOptions() + checkAccomp();
    
        $('#TotalPrice').text(ThePrice);
    }
    
    $(function () { $('.DoPricing').click(updateTotal); });
    

    Here's the working jsFiddle. I didn't add all the ids and corresponding prices to the OptionPricing object but you get the idea. Also, if the prices change, or if new prices are added, this pattern should be easier to maintain, not to mention that the code is considerably reduced to just a few lines (and could even be reduced a bit further if you like terse syntax). I used jQuery (you had the tag in the question) but you could easily modify it and use plain js if needed.

提交回复
热议问题