-2

在 javascript 中有一个小的 if/else 问题。没看懂逻辑。。。

该函数应检查是否存在两个日期,如果不存在则发出警报。如果一切正常,它应该这样说......

function update_booking() {
    //from_date = The date of arrival
    //to_date = The date of departure

    var alert = ""; //reset alerts

    //get variables from booking form input
    var from_date = new Date(document.getElementById('from').value);
    var to_date = new Date(document.getElementById('to').value);

    //if arrival and departure date is present
    if(from_date && to_date) {
        var alert = "Everything is OK";
    }

    //if one or two dates are missing
    else {
        //if arrival and departure dates are missing
        if(from_date == 'undefined' || to_date == 'undefined'){
            var alert = "Arrival date and departure date are missing";  
        }

        //if from_date is missing update with value from to_date
        if(from_date == 'undefined') {
            var alert = "Arrival date are missing";
        }

        //if to_date is missing update with value from from_date
        if(from_date == 'undefined') {
            var alert = "Departure date are missing";
        }
    } //end else if one or more date(s) missing

    //write alerts
    document.getElementById('alert').innerHTML = alert;
}
4

3 回答 3

3

如果 Date 的值无效,则new Date(datestring)返回一个不是数字 (NaN) 的对象。

例如,两者都new Date("")返回new Date(" ")一个对象,它是 NaN,而new Date("04-29-2013")不是。

因此,我建议将搜索更改为undefinedNaN isNaN(),如下所示:

if(isNaN(from_date) || isNaN(to_date)){
于 2013-04-29T18:10:58.737 回答
1

new Date不会回来undefined

> new Date("")
Invalid Date

所以看看你的代码

if(from_date == 'undefined' || to_date == 'undefined'){

它永远不会进入那个 if 语句。

要检查日期是否有效,您需要将isNaN 与 getTime()一起使用

于 2013-04-29T18:03:35.013 回答
0

尝试这个:

function update_booking() {
//from_date = The date of arrival
//to_date = The date of departure
//get variables from booking form input
var from_date = document.getElementById('from').value;
var to_date =document.getElementById('to').value;

//if arrival and departure date is present
if(from_date && to_date) {
    alert( "Everything is OK");
}

//if one or two dates are missing
else {
    //if arrival and departure dates are missing
    if(from_date == ""|| to_date == ""){
        alert("Arrival date or departure date are missing");  
    }

    //if from_date is missing update with value from to_date
    if(from_date == "") {
        alert("Arrival date are missing");
    }

    //if to_date is missing update with value from from_date
    if(to_date == "") {
        alert("Departure date are missing");
    }
} //end else if one or more date(s) missing

}

于 2013-04-29T18:22:06.420 回答