最近我问了一个类似的问题,但我会删除它,因为它不够清楚,我的不好。
我需要从多个动态对象中获取年,月和日期值
Object {year: 2017, month: 1, date: 26}
Object {year: 2017, month: 2, date: 5}
Object {year: 2017, month: 2, date: 12}
Object {year: 2017, month: 2, date: 19}
Object {year: 2017, month: 2, date: 26}
我需要像这样在数组中制作它们:
[26/1/2017, 5/2/2017, 12/2/2017, 19/2/2017, 26/2/2017]
然后,使用该数组将这些值放入输入隐藏值中,如下所示:
<input type="hidden" value="26/1/2017, 5/2/2017, 12/2/2017, 19/2/2017, 26/2/2017">
我设法获取值并将它们推送到数组中,但我无法让它们按原样运行,这是我的代码:
// Note: This code is in each function
// This holds the objects
var sundayData = $(this).data();
// I get date, month and year values
var dayAll = sundayData['date'];
var monthAll = sundayData['month'];
var yearAll = sundayData['year'];
// Here, I putting them in the right format
var sundayDatesAll = dayAll + '/' + (monthAll + 1) + '/' + yearAll;
//
var sundayDate = [];
// Here, I push the dates in sundayDate
sundayDate.push(sundayDatesAll);
$('input').val(sundayDate.join());
但是,像这样,它会像这样返回分离的数组:
["26/2/2017"]
["5/3/2017"]
["12/3/2017"]
["19/3/2017"]
["26/3/2017"]
并且输入中只有一个值,我认为它是最后一个值26/3/2017
感谢任何帮助,谢谢......
答案 0 :(得分:1)
您需要获取输入的旧值,拆分它,然后将新日期添加到它,而不是每次都以空数组开头。
var sundayDate = $('input').val().split(',');
// Here, I push the dates in sundayDate
sundayDate.push(sundayDatesAll);
$('input').val(sundayDate.join(','));
您可以将其合并到:
$('input').val(function(i, oldDates) {
var sundayDate = oldDates.split(',');
sundayDate.push(sundayDatesAll);
return sundayDate.join(',');
});