javascript - 如何在javascript中将两个计算函数合并在一起

标签 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("total")[0].value = "$" + total ; and document.getElementsByName("total")[0].value = "$" + sc ;

并将两者合并在一起

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

它给了我一个错误“total or sc is underfine”。
有什么建议或提示可以让我得到两者计算的总和吗?

最佳答案

我正在使用一些您可能尚未遇到过的函数,但我已尝试添加足够的注释来解释发生的情况。

// 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 ) {
	// We want to sum all the checkboxes, so we can just select them all out of the wrapper.
	// 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.
	var checkedBoxes = Array.prototype.slice.call( checkboxWrapper.querySelectorAll('input:checked') );
	// The total of the checkboxes is just a reduction from many checkboxes to one number. This is similar to a for loop.
	var boxPrice = checkedBoxes.reduce(function( total, box ) {
		// Notice how we don't use floating point numbers here.
		// It's VERY important to not do calculations with floats when you work with money
		// Rounding errors can make the total be off, which leads to unhappy customers.
		// So we do all maths with integers and just divide the total by 100 in the end.
		var price = parseInt(box.getAttribute('data-price'), 10);
		total += price;
		return total;
	}, 0);
	// 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.
	// 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.
	var checkedRadio = radioWrapper.querySelector('input:checked');
	// If there is no radio selected, the radio price is automatically 0
	// We can use a ternary here. This is just shorthand for: "if (checkedRadio) radioPrice = parseInt(checkedRadio.getAttribute('data-price'), 10); else radioPrice = 0;"
	var radioPrice = (checkedRadio) ? parseInt(checkedRadio.getAttribute('data-price'), 10) : 0;
	// Calculate the total price string, divide it by 100 so we have dollars again instead of cents and add/remove any trailing zeroes.
	// Always do the maths first, then determine how the result should be visualized.
	var realPriceString = '$' + ((boxPrice + radioPrice) / 100).toFixed(2);
	// Render the total price.
	document.querySelector('#total').innerHTML = realPriceString
	
	
	
}
// 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);
	<div id="prices-checkboxes">
		<input type="checkbox" data-price="1514">$15.14</input>
		<input type="checkbox" data-price="2556">$25.56</input>
		<input type="checkbox" data-price="3574">$35.74</input>
		<input type="checkbox" data-price="4556">$45.56</input>
	</div>
	<div id="prices-radios">
		<input type="radio" name="radio-price" data-price="0">$0.00</input>
		<input type="radio" name="radio-price" data-price="1478">$14.78</input>
		<input type="radio" name="radio-price" data-price="7481">$74.81</input>
		<input type="radio" name="radio-price" data-price="2545">$25.45</input>
		<input type="radio" name="radio-price" data-price="7812">$78.12</input>
	</div>
	<div id="total">$0.00</div>

关于javascript - 如何在javascript中将两个计算函数合并在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43226102/

相关文章:

javascript - 尝试设置输入 node.js puppeteer 的值时出现未定义错误

php - Curl 和 javascript 提交

javascript - Powershell网站自动化: Javascript Popup Box Freeze

javascript - 使用 Javascript 嵌入包含 &lt;script&gt; 的 MvcHtmlString

javascript - 如何在javascript中以所需的格式移动数组中的数据?

javascript - 如何对多个 Firebase 子节点进行平均投票?

Javascript 函数最后有(文档)吗?

javascript - 获取与选择器匹配的所有元素,将它们放入对话框中,隐藏页面上的其他所有内容

javascript - 单击另一个时如何折叠打开的常见问题解答?

javascript - "if ( somefunction( ) )"在 node.js 中阻塞了吗?