2017-04-05 55 views
0

首先,我有2种计算函数
第一个处理复选框,第二个处理收音机
我想在文本中显示总计算框。
下面的示例工作,但它会覆盖对方,当我没有选中它。如何在javascript中合并两个计算函数

//calculate price 
var checks = document.getElementsByName('e'); 
for (var i = 0; i < checks.length; i++) 
    checks[i].onclick = function() { 
     var cal = document.getElementsByName('e'); 
     var total = 0; 
     for (var i = 0; i < cal.length; i++) { 
      if (cal[i].checked) 
       total += parseFloat(cal[i].getAttribute('data')); 
     } 
     document.getElementsByName('total')[0].value = '$' + total; 
    } 

//calculate radio price 
var tick = document.getElementsByName('d'); 
tick.forEach(function (value) { 
    if (value.checked) 
     document.getElementsByName('total')[0].value = '$' + value.getAttribute('data'); 
}) 
for (var i = 0; i < tick.length; i++) 
    tick[i].onclick = function() { 
     var rad = document.getElementsByName('d'); 
     var sc = 0; 
     for (var i = 0; i < rad.length; i++) { 
      if (rad[i].checked) 
       sc += parseFloat(rad[i].getAttribute('data')); 
     } 
     document.getElementsByName('total')[0].value = '$' + sc; 
    } 

但是当我试图让两个值的总和被除去

document.getElementsByName( “总”)[0]。价值= “$” +总; 和document.getElementsByName(“total”)[0] .value =“$”+ sc;

和由

document.getElementsByName( “总”)一起合并两者的它[0]。价值= “$” +总+ SC;

它给了我一个错误“total或sc underfine”。
是否有任何建议或提示让我得到两者的总和?

+0

您可以通过将事件的复选框和收音机的父元素简化代码了很多东西。那么你只需要添加一次事件而不是每个元素。也可以使用'addEventListener('click')'而不是element.onclick = function(){}'将多个函数绑定到同一个元素,而不是覆盖事件。 – Shilly

+0

你能举个例子吗?我是新来的JavaScript,我仍然cnt解决这个问题 – ccs

回答

1

我使用了一些你可能没有遇到的函数红色,但我已经尝试添加足够的评论来解释发生了什么。

// Grab the divs that contains the checkboxes and radios 
 
// document.querySelector can replace getElementById/Name/ClassName using the same syntax as css selectors. 
 
var checkboxWrapper = document.querySelector('#prices-checkboxes'); 
 
var radioWrapper = document.querySelector('#prices-radios'); 
 
// Let's make one counting function that handles both the cechkboxes and the radios. 
 
// Since it will be an event handler, it will have an 'event' object as its first parameter. 
 
var calculatePrice = function(event) { 
 
\t // We want to sum all the checkboxes, so we can just select them all out of the wrapper. 
 
\t // But we get an html collection, where we want an array, so we can cast it to an array as well at the same time. 
 
\t var checkedBoxes = Array.prototype.slice.call(checkboxWrapper.querySelectorAll('input:checked')); 
 
\t // The total of the checkboxes is just a reduction from many checkboxes to one number. This is similar to a for loop. 
 
\t var boxPrice = checkedBoxes.reduce(function(total, box) { 
 
\t \t // Notice how we don't use floating point numbers here. 
 
\t \t // It's VERY important to not do calculations with floats when you work with money 
 
\t \t // Rounding errors can make the total be off, which leads to unhappy customers. 
 
\t \t // So we do all maths with integers and just divide the total by 100 in the end. 
 
\t \t var price = parseInt(box.getAttribute('data-price'), 10); 
 
\t \t total += price; 
 
\t \t return total; 
 
\t }, 0); 
 
\t // We also want the radio button that is checked, if any. Since radio buttons with the same name belong to the same group, this will always be only ONE radio. 
 
\t // So we can use querySelector instead of querySelectorAll so we only get One element instead of a collection we need to cast to an array. 
 
\t var checkedRadio = radioWrapper.querySelector('input:checked'); 
 
\t // If there is no radio selected, the radio price is automatically 0 
 
\t // We can use a ternary here. This is just shorthand for: "if (checkedRadio) radioPrice = parseInt(checkedRadio.getAttribute('data-price'), 10); else radioPrice = 0;" 
 
\t var radioPrice = (checkedRadio) ? parseInt(checkedRadio.getAttribute('data-price'), 10) : 0; 
 
\t // Calculate the total price string, divide it by 100 so we have dollars again instead of cents and add/remove any trailing zeroes. 
 
\t // Always do the maths first, then determine how the result should be visualized. 
 
\t var realPriceString = '$' + ((boxPrice + radioPrice)/100).toFixed(2); 
 
\t // Render the total price. 
 
\t document.querySelector('#total').innerHTML = realPriceString 
 
\t 
 
\t 
 
\t 
 
} 
 
// We want to add the event handler to the wrappers themselves. This way we only have to add it once, instead of for each checkbox and radio. 
 
// addEventListener gives you more control than onclick, since onclick handlers will overwrite eachother. 
 
checkboxWrapper.addEventListener('click', calculatePrice); 
 
radioWrapper.addEventListener('click', calculatePrice);
\t <div id="prices-checkboxes"> 
 
\t \t <input type="checkbox" data-price="1514">$15.14</input> 
 
\t \t <input type="checkbox" data-price="2556">$25.56</input> 
 
\t \t <input type="checkbox" data-price="3574">$35.74</input> 
 
\t \t <input type="checkbox" data-price="4556">$45.56</input> 
 
\t </div> 
 
\t <div id="prices-radios"> 
 
\t \t <input type="radio" name="radio-price" data-price="0">$0.00</input> 
 
\t \t <input type="radio" name="radio-price" data-price="1478">$14.78</input> 
 
\t \t <input type="radio" name="radio-price" data-price="7481">$74.81</input> 
 
\t \t <input type="radio" name="radio-price" data-price="2545">$25.45</input> 
 
\t \t <input type="radio" name="radio-price" data-price="7812">$78.12</input> 
 
\t </div> 
 
\t <div id="total">$0.00</div>

0

尝试在forloops之外声明总数和sc。 您可以在上面 宣布他们可能是这一步

var checks = document.getElementsByName('e');

0

有一个共同的变量作为最终总并分配给

var Finaltotal =0; 

    var checks = document.getElementsByName('e'); 
    for (var i = 0; i < checks.length; i++) 
     checks[i].onclick = function() { 
    var cal = document.getElementsByName('e'); 
    var total = 0; 
    for (var i = 0; i < cal.length; i++) { 
     if (cal[i].checked) 
     total += parseFloat(cal[i].getAttribute("data")); 

    } 
Finaltotal = total; 
    document.getElementsByName("total")[0].value = "$" + total ; 

} 

//calculate radio price 
    var tick = document.getElementsByName('d'); 
    tick.forEach(function(value){ 
     if (value.checked) 
      document.getElementsByName("total")[0].value ="$" + value.getAttribute('data'); 

}) 
for (var i = 0; i < tick.length; i++) 
    tick[i].onclick = function() { 
    var rad = document.getElementsByName('d'); 
    var sc = 0; 
    for (var i = 0; i < rad.length; i++) { 
    if (rad[i].checked) 
     sc += parseFloat(rad[i].getAttribute("data")); 

    } 
    document.getElementsByName("total")[0].value = "$" + sc ; 
Finaltotal = Finaltotal + sc ; 
} 

希望这将帮助你后

相关问题