我的Javascript验证没有';虽然不能在Firefox和Safari上运行,但在Chrome、UC浏览器和其他浏览器上运行良好
我制作了一个用于计算孕龄的网络应用程序,在Chrome上运行正常。但是,它为${dateString}值显示无效日期,${GestationAge}值显示NaN我的Javascript验证没有';虽然不能在Firefox和Safari上运行,但在Chrome、UC浏览器和其他浏览器上运行良好,javascript,validation,web-applications,Javascript,Validation,Web Applications,我制作了一个用于计算孕龄的网络应用程序,在Chrome上运行正常。但是,它为${dateString}值显示无效日期,${GestationAge}值显示NaN //DEFINE DATE const dateValue = document.querySelector('.datepicker'); const message = document.querySelector('.message'); function getDate(e) { //INPUT VALUE OF DAT
//DEFINE DATE
const dateValue = document.querySelector('.datepicker');
const message = document.querySelector('.message');
function getDate(e) {
//INPUT VALUE OF DATE ASSIGNMENT
const dateV = dateValue.value;
//CONVERTING DATE INPUT FORMAT INTO DAY,DATE,MONTH & YEAR
const dateResult = new Date(dateV);
//USING FORMULA FOR CALCULATING EDD, FIRSTLY SUBTRACT 3 MONTHS
dateResult.setMonth(dateResult.getMonth() - 3);
//console.log(dateResult);
//THEN ADD A YEAR
dateResult.setFullYear(dateResult.getFullYear() + 1);
//console.log(dateResult);
//FINALLY ADD 7 DAYS
dateResult.setDate(dateResult.getDate() + 7);
const dateString = dateResult.toDateString();
if (!(new Date(dateV) >= new Date()) && (dateV !== '')) {
//CALCULATING GESTATIONAL AGE USING CURRENT DATE AND DATE OF LMP
const ga = Math.abs(new Date() - new Date(dateV));
//CONVERTING THE MILLISECONDS FROM ABOVE INTO DAYS
const gaFu = Math.ceil(ga / (1000 * 60 * 60 * 24));
//CONVERTING THE DAYS INTO WEEKS
//I DIDN'T SPECIFY DAYS + WEEKS BUT I ASSUME IT'LL HAVE TO DO WITH AN IF STATEMENT UPON THE DECIMALS
const gaFull = gaFu / 7;
const gestationalAge = Math.floor(gaFull);
//OUTPUT THE ANSWER TO RESULT
message.style.color = 'yellow';
message.textContent = ` Your expected delivery date is ${dateString} & you are ${gestationalAge} week(s) pregnant`;
//console.log(dateResult);
} else if (dateV === '') {
M.toast({ html: 'Invalid Date!' });
} else {
//INCASE OF ERROR
message.style.color = 'blue';
message.textContent = `You're from the future are'nt you? `;
}
e.preventDefault();
}
//EVENT LISTENER
document.querySelector('form').addEventListener('submit', getDate);
如果代码不可读,我道歉。我对javascript比较陌生dateValue.value的值是多少?在不知道输入值的情况下很难复制…dateValue.value是从UI中的datepicker输入定义的第一行。它是从datepicker输入的值。您描述的行为很可能是由
新日期(dateV)
未产生好日期引起的。为了找出原因,了解dateV
的字符串值实际上是什么非常重要。可能是非标准格式,一些浏览器无法识别。或者浏览器之间的区域设置可能有问题。也许你可以在你的代码中添加一个console.log(dateValue.value)
,这样你就可以看到字符串值实际上是什么样子了?控制台日志dateValue.value又名dateV的格式示例是“13-04-2020”,所以我不知道这对firefox和safari来说是否是不可读的格式。但是,我最终使用.toDateString()转换它,这就是它最终在UI中显示的方式。感谢您的回复,所以请注意,更改日期格式可以解决此问题