拆分方法:返回不同的部分

时间:2013-03-18 03:45:34

标签: javascript methods split

我想要做的是当用户以MM / DD / YYYY的形式输入日期时,我的闰年功能仅返回年份值。现在,我只使用它一年,但我希望该功能要求用户输入该表格中的日期并计算它是否是闰年。如何修改当前代码以执行此操作。我用split方法声明了一个新变量。谢谢!

function isLeaper() {
            var year = document.getElementById("isLeaper").value;
            var splitYear = year.split ('/');
            // 1. If the year is divisible by 4, but not 100.
            if ((parseInt(splitYear) % 4) == 0) {
                if (parseInt(splitYear) % 100 == 0) {
                    if (parseInt(splitYear) % 400 != 0) {
                        alert(year + 'is not a leap year. Sorry!');
                        return "false";
                    }
                    if (parseInt(splitYear) % 400 == 0) {
                        alert(year + 'is a leap year. Hooray!');
                        return "true";
                    }
                }
                if (parseInt(splitYear) % 100 != 0) {
                    alert(year + 'is a leap year. Hooray!');
                        return "true";
                }
            }
            if ((parseInt(splitYear) % 4) != 0) {
                alert(year + 'is not a leap year. Sorry!');
                        return "false";
            }
        }

1 个答案:

答案 0 :(得分:0)

更改

var year = document.getElementById("isLeaper").value;
var splitYear = year.split ('/');

var year = document.getElementById("isLeaper").value;
var arr = year.split('/');
var splitYear = arr[arr.length - 1];

如果变量year的形式为MM / DD / YYYY和YYYY,则会获得年份。

你可以试试这个:

$('#yourContainerID').html(year + 'is not a leap year. Sorry!').fadeIn('normal',function(){
    $(this).fadeOut();
});

有关详细信息,请参阅.fadeIn().fadeOut()