如何显示聚合物

时间:2018-02-20 07:19:31

标签: javascript html polymer

如何在聚合物上显示以前的日期到今天和接下来的日期多年? 我尝试了以下脚本,但它无法正常工作 我只在昨天和明天的日期在控制台上重复。我希望前一天前一个,依此类推。此外,我不能追溯到今天。

<header>
  <iron-icon class="icon" icon="chevron-left" on-tap="previousDay" suffix></iron-icon>
  <iron-icon class="icon" icon="chevron-right" on-tap="nextDay" suffix></iron-icon>
</header>
<br/><br/>       



nextDay: function() {
  var currentDay = new Date(); 
  currentDay.setDate(currentDay.getDate() + 1);
  console.log(currentDay);
},

previousDay: function () {
  var currentDay = new Date();
  currentDay.setDate(currentDay.getDate() - 1);
  console.log(currentDay);
},

2 个答案:

答案 0 :(得分:2)

可能的解决方案是:

nextDays: function() {
    var currentDay = new Date();
    var nextDays = [];

    for (var i = 1; i <= 30; i++) {
        var newDate = new Date();
        newDate.setDate(currentDay.getDate() + i);
        nextDays.push(newDate);
    }

    // nextDays will contain the 30 next days
}

previousDays: function() {
    var currentDay = new Date();
    var previousDays = [];

    for (var i = 1; i <= 30; i++) {
        var newDate = new Date();
        newDate.setDate(currentDay.getDate() - i);
        previousDays.push(newDate);
    }

    // previousDays will contain the 30 last days
}

您只需更改所需的天数(本例中为30天),然后使用数组nextDayspreviousDays执行您想要的操作。

您可以添加的内容就是这些天的缓存,这样您就不必每次都生成它们(特别是如果它在同一天生成)。

答案 1 :(得分:1)

这是一个使用私有变量的简单解决方案。

&#13;
&#13;
var date = (() => {
  var currentDay = new Date();
  
  function previousDay() {
    currentDay.setDate(currentDay.getDate() - 1);
    return currentDay;
  }
  
  function nextDay() {
    currentDay.setDate(currentDay.getDate() + 1);
    return currentDay;
  }
  
  return { previousDay, nextDay };
})();
&#13;
<button onclick="console.log(date.previousDay())">Previous day</button>
<button onclick="console.log(date.nextDay())">Next day</button>
&#13;
&#13;
&#13;

你甚至可以缩短它,两者都可以使用相同的功能:

&#13;
&#13;
var date = (() => {
  var currentDay = new Date(),
    previousDay = () => goToDay(-1),
    nextDay = () => goToDay(1);
    
  function goToDay(n) {
    currentDay.setDate(currentDay.getDate() + n);
    return currentDay;
  }
  
  return { previousDay, nextDay };
})();
&#13;
<button onclick="console.log(date.previousDay())">Previous day</button>
<button onclick="console.log(date.nextDay())">Next day</button>
&#13;
&#13;
&#13;