Javascript 获取日期并循环到组合框

标签 javascript jquery

对于这种情况,我不想使用 jQuery 日期时间选择器。因为我制作移动应用程序。

[我的案例]我正在使用 javascript 来获取今天和接下来几天的日期的值。但我想要更灵活,希望使用 jquery 将数据显示在双循环上并显示到组合框中。

直到今天,我使用以下方式获取数据:

function GetDay(){
     var today = new Date();
     var dd = today.getDate();
     var mm = today.getMonth()+1; //January is 0!
     var yyyy = today.getFullYear();
     if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = yyyy+'-'+mm+'-'+dd;
     alert(today);
}

Result : 2013-04-28

对于我来说第二天使用:

function NextDay1(){
    var today = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} next1 = yyyy+'-'+mm+'-'+dd;
    alert(next1);
}

Result : 2013-04-29

我使用的方式是非常手动的,如果我想获取数据:

2013-04-28
2013-04-29
2013-04-30
2013-05-01
2013-05-02
ect...

我使用的方式是非常手动的,如果我想获取这样的数据并放置一个组合框来选择该日期?

最佳答案

您可以像这样循环获取日期:

// Create an empty array to store the dates generated
var myDates = [];

// Loop through for 5 times here
for (var i = 0; i < 5; i++) {
    var myDate = new Date();
    var fullDate = new Date(myDate.setDate(myDate.getDate() + i));
    var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
    var twoDigitDates = ('0' + fullDate.getDate()).slice(-2);
    var currentDate = fullDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDates;
    myDates.push(currentDate);
}

// Check the dates in console as an array
console.log(myDates);

然后插入到下拉列表中,例如:

// Loop through the date array we have created
$.each(myDates, function (index, item) {

    // Add options to the select list
    $('#mySelect').append($('<option>', {
        value: index,
        text: item
    }));
});

关于Javascript 获取日期并循环到组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16262591/

相关文章:

javascript - 如何测试传递给函数的变量?

javascript - 多次滑动函数调用

javascript - 改进 Javascript 中的数组转换

javascript - 在解析时使用变量过滤数据

php - 在 Safari/Mac 中需要有关 jQuery/AJAX 调用的帮助

javascript - Android Chrome 在旋转屏幕后使用 javascript 退出全屏后隐藏地址栏(错误?)

javascript - 为什么在页面首次加载时无法在 backbone 中获取元素的大小?

javascript - LocalStorage追加新元素

javascript - 如何避免多次发送表单

javascript - HTML 和 JavaScript - Bootstrap