如何在页面加载时进行JavaScript计算?

如何在页面加载时进行JavaScript计算?,javascript,html,Javascript,Html,我建立了一个财务计算器,我已经预先检查了HTML中的值。一个是60个月的融资期限,另一个是10%的首付款 链接到。 当页面加载时,计算器尚未计算值,因为要这样做,用户必须选择值,然后点击计算 是否有一种方法可以加载一页,加载选定值60%和10%的总计算值 提前谢谢你 index.js //定义产品价格 const productPrice=105000; //将产品价格附加到DOM const productPriceID=document.getElementById(“产品价格”); pro

我建立了一个财务计算器,我已经预先检查了HTML中的值。一个是60个月的融资期限,另一个是10%的首付款

链接到。

当页面加载时,计算器尚未计算值,因为要这样做,用户必须选择值,然后点击计算

是否有一种方法可以加载一页,加载选定值60%和10%的总计算值

提前谢谢你

index.js
//定义产品价格
const productPrice=105000;
//将产品价格附加到DOM
const productPriceID=document.getElementById(“产品价格”);
productPriceID.innerHTML=productPrice.toLocaleString();
//抓取主要产品价格、首付款、总金额、每月id和DOM追加按钮
const downPaymentValue=document.getElementById(“首期付款值”);
const totalValue=document.getElementById(“总值”);
const perMonthValue=document.getElementById(“每月值”);
const calculateBtn=document.getElementById(“计算”);
/////////计算
calculateBtn.addEventListener(“单击”,计算);
函数计算(){
//获取所选月份的值
const monthSelected=document.querySelector('input[name=“month”]:checked')
价值
//获取所选首付百分比的值
const percentageSelected=document.querySelector(
'输入[name=“percent”]:选中'
).价值;
//根据主价格计算首付百分比
const totalDownPayment=产品价格*所选百分比;
//计算总数
const totalPrice=productPrice-总首付款;
//计算每月的费用
const perMonth=总价格/所选月份;
//使用options参数转换为文本以指定小数位数
const totalDownPaymentStr=totalDownPayment.toLocaleString(
navigator.language,
{最小分数位数:2,最大分数位数:2}
);
const totalPrice str=totalPrice.toLocaleString(navigator.language{
最小分数位数:2,
最大分数位数:2
});
const perMonthStr=perMonth.toLocaleString(navigator.language{
最小分数位数:2,
最大分数位数:2
});
//向DOM追加首付款
downPaymentValue.innerHTML=
“$”+totalDownPaymentStr.toLocaleString();
downPaymentValue.parentNode.appendChild(downPaymentValue);
//向DOM追加总计
totalValue.innerHTML=“$”+totalPriceStr.toLocaleString();
totalValue.parentNode.appendChild(totalValue);
//每月追加到DOM
perMonthValue.innerHTML=“$”+perMonthStr.toLocaleString();
perMonthValue.parentNode.appendChild(perMonthValue);
}
/////////可达性
//抓取所有标签
const allLabels=document.queryselectoral(“标签”);
//在enter键上,仅选择所选的
allLabels.forEach(label=>label.addEventListener(“keyup”,onEnter));
函数集合(e){
e、 预防默认值();
如果(如keyCode===13){
这个。单击();
}
}

计算
函数之前添加此行:

window.onload = calculate();

计算
函数之前添加此行:

window.onload = calculate();

将全局变量定义为预先检查的60%和10%值后,您可以调用“calculate()”函数


链接到

在将全局变量定义为预先检查的60%和10%值后,只需调用“calculate()”函数即可


链接到

在index.js文件的末尾,您可以调用
计算
方法(即
计算();
)。我在你的沙箱里试过了,它似乎奏效了。@DanielWStrimpel哈哈,哇。这完全可以做到。非常感谢丹尼尔!在index.js文件的末尾,您可以调用
计算方法(即
计算();
)。我在你的沙箱里试过了,它似乎奏效了。@DanielWStrimpel哈哈,哇。这完全可以做到。非常感谢丹尼尔
window.onload
只能执行一个函数,因此此行将替换已附加到
window.onload
的任何内容。使用
window.addEventListener(“加载”,计算)更安全
window.onload
只能执行一个函数,因此此行将替换已附加到
window.onload
的任何内容。使用
window.addEventListener(“加载”,计算)更安全