2015-08-14 39 views
0

我使用下面的函數來計算產品的總價格:爲什麼jQuery在應用函數之前清空div?

jQuery(document).ready(function() { 
    function j_updateprice() { 
    var p = 0; 
    jQuery('.am-signup-form input[type=radio][id^=product]:checked, 
      .am-signup-form input[type=checkbox][id^=product]:checked') 
    .each(function(i, v) { 
     if (jQuery(v).attr('data-first_price')) { 
     p += parseFloat(jQuery(v).attr('data-first_price')); 
     } 
    }); 
    jQuery('#j_price').text(p.toFixed(2)); 
    } 

    jQuery('.am-signup-form input[type=radio][id^=product], 
      .am-signup-form input[type=checkbox][id^=product]') 
    .change(function() { 
    j_updateprice(); 
    }); 

    j_updateprice(); 
}); 

的問題是,當我在另一個div的,價格只是不斷累加的複選框/單選按鈕點擊(它不該「T)。所以,我認爲j_updateprice()被應用前的總(#j_price)排空:

jQuery('.am-signup-form input[type=radio][id^=product], 
      .am-signup-form input[type=checkbox][id^=product]') 
    .change(function() { 
    jQuery('#j_price').empty(); 
    j_updateprice(); 
    }); 

但沒有任何反應。價格只是加起來。這是爲什麼?

直播現場:http://www.chineselearnonline.com/amember/signup

+0

您需要在取消選中某個項目時從「p」變量中減去。 –

+1

沒有關係,但我覺得'。數據(「first_price」)'是在參訪'.attr(「數據first_price」)' – RRK

+0

@Joshua Coussard對不起,我沒有很好地理解。你能提供一個例子嗎? – alexchenco

回答

3

您應該考慮選擇面板中選中的元素,現在你正在考慮的形式內的所有檢查項目,其中將包括在一個選定的面板也

jQuery(document).ready(function() { 
    function j_updateprice() { 
     var p = 0; 
     jQuery('.am-signup-form .panel-expanded input[type=radio][id^=product]:checked, .am-signup-form .panel-expanded input[type=checkbox][id^=product]:checked').each(function (i, v) { 
      if (jQuery(v).attr('data-first_price')) p += parseFloat(jQuery(v).attr('data-first_price')); 
     }); 
     jQuery('#j_price').text(p.toFixed(2)); 
    } 

    jQuery('.am-signup-form input[type=radio][id^=product], .am-signup-form input[type=checkbox][id^=product]').change(function() { 
     j_updateprice(); 
    }); 

    j_updateprice(); 
}); 
項目

注意:當選定面板改變時,您還必須致電j_updateprice

+0

@謝謝你的回答!至於說明,不是這一行:'jQuery('。am-signup-form input [type = radio] [id^= product],.am-signup-form input [type = checkbox] [id^=產品]')'做到這一點? – alexchenco

+0

我沒有看到這個問題。我唯一擁有的是默認價格(一個單選按鈕)在頁面首次加載時並未顯示在總價中。 – alexchenco

+0

@alexchenco它是選擇的形式內的所有檢查的項目'AM-註冊-form' ...但我猜你要選擇的'面板login'內僅選擇項目 –

相關問題