【问题标题】:Split Method: returning different parts拆分方法:返回不同的部分
【发布时间】:2013-03-18 03:45:34
【问题描述】:

我想要做的是当用户以 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";
            }
        }

【问题讨论】:

  • 试试console.log(splitYear)你可能会发现。

标签: javascript methods split


【解决方案1】:

改变

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()

【讨论】:

  • 效果很好!谢谢您的帮助。我知道我快到了,但我错过了如何恢复分裂的部分。再次感谢!!
  • 另外,现在,分析器显示在警报中。你知道如何使用 JQuery 显示和缓慢淡出来显示答案而不是警报吗?我不知道如何使用 JQuery。
  • @AlanJosephSylvestre 请查看我的帖子。
  • 太棒了!但是,我为容器 id 输入了什么?一个div标签的id?
  • @AlanJosephSylvestre 是的,您想要的 div 将您的消息放入其中。
猜你喜欢
  • 1970-01-01
  • 2017-07-26
  • 2020-11-20
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 2019-11-21
  • 1970-01-01
  • 2010-10-25
相关资源
最近更新 更多