简体   繁体   中英

Why does this addition or substract don't work?

I try to create a price total,i have lot of products(10) and all have buttons (add : +1 and subtract: -1)for each i do price*quantity, now i want to create a total (just a span which show price total ). This code add price to total but not subtract and when i click on button, just one price is add the first of i have click.

var veste = 0, pantalon = 0, chemise = 0, chemise_pliee = 0, robe = 0, 
    manteau = 0, blouson = 0, pull = 0, cravate = 0, couette = 0;

var qt_articles = [];
var tab_prix = [];
var prix_global = parseFloat(document.getElementById('prix_global').innerHTML);

function print_nb_article(article, nb) {
    $('#top_ten_nb_'+article).text(nb);
    var prix = $('#top_ten_nb_'+article+'_prix').val();
    var prix_tt = prix * nb;
    $('.prix_'+article).text(prix_tt);


    if (prix_tt > 0) tab_prix.push(prix_tt);
    for(i=0; i<=tab_prix.length; i++) {

        if ('#plus_'+article)
            prix_global += parseFloat(tab_prix[i]);
        document.getElementById('prix_global').innerHTML = prix_global;

        return false;
    }
}


$('#plus_veste').click(function() {
    veste++;
    print_nb_article('veste', veste);
    return false;
});  

$('#moins_veste').click(function() {
    veste--;
    print_nb_article('veste', veste);
    return false;
});

$('#plus_chemise_pliee').click(function() {
    chemise_pliee++;
    print_nb_article('chemise_pliee', chemise_pliee);
    return false;
});  

$('#moins_chemise_pliee').click(function() {
    chemise_pliee--;
    print_nb_article('chemise_pliee', chemise_pliee);
    return false;
});

...

I can't find the problem, Somebody can help me ?

Could the problem be missing braces around your if block?

if ('#plus_'+article) {
  prix_global += parseFloat(tab_prix[i]);
  document.getElementById('prix_global').innerHTML = prix_global;
}

Is that what you intended? FWIW, I always use braces, even for one-liners. It not only prevents errors (if indeed this is one), it also clarifies your intent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM