我的代码需要一些帮助。我有一个前进按钮和后退按钮,据说动态显示一周到下一个,反之亦然。我在加载时显示当前周。问题是我似乎无法弄清楚如何使前进和后退按钮从一周范围连续移动到另一周。这是我的代码:
<html>
<head>
<link rel="stylesheet" type="text/css" href="calendar.css">
<title>Calendar</title>
</head>
<body onload="dateRange()">
<script>
function dateRange(){
var start_date = "<?php echo $start_date = date("F d Y",strtotime('monday this week')); ?>";
var end_date = "<?php echo $end_date = date("F d Y",strtotime("sunday this week"));; ?>";
document.getElementById('date_range').innerHTML = start_date + " - " + end_date;
}
function forward(){
var start_date = "<?php echo $start_date = date('F d Y', strtotime('+1 weeks', strtotime($start_date))); ?>";
var end_date = "<?php echo date('F d Y', strtotime('+1 weeks', strtotime($end_date))); ?>";
document.getElementById('date_range').innerHTML = start_date + " - " + end_date;
}
function backward(){
var start_date = "<?php echo date('F d Y', strtotime('-1 weeks', strtotime($start_date))); ?>";
var end_date = "<?php echo date('F d Y', strtotime('-1 weeks', strtotime($end_date))); ?>";
document.getElementById('date_range').innerHTML = start_date + " - " + end_date;
}
</script>
<h1 id="date_range"></h1>
<div>
<input type="button" onClick="forward()" name="forward" value=">">
<input type="button" onClick="backward()" name="backward" value="<">
</div>
真的可以使用帮助,非常感谢。
答案 0 :(得分:0)
第一件事:使用PHP填充你的javascript并不是一个好习惯。 PHP是一种服务器端语言,javascript(在本例中)在客户端浏览器中运行。这将使您的代码很难维护和调试,因为您需要深入了解脚本以了解PHP如何输出它。
你可以用javascript完成所有这些:
<强> HTML 强>
<body>
<h1 id="date_range"></h1>
<div>
<input type="button" onClick="backward()" name="backward" value="<">
<input type="button" onClick="forward()" name="forward" value=">">
</div>
</body>
<强>的Javascript 强>
var range = document.getElementById('date_range');
var offset = 0;
var today = new Date();
var dayOfWeekOffset = today.getDay();
function getWeek(offset) {
offset = offset || 0; // if the function did not supply a new offset, the offset is 0
var firstDay = new Date();
firstDay.setDate(firstDay.getDate() - dayOfWeekOffset + (offset * 7));
// .setDate() sets the date (1-31) of the current month.
// The beginning of the week is:
// today's date (firstDay.getDate())
// minus the day of week offset to get us back to sunday (dayOfWeekOffset)
// plus the number of days we need to offset for future / past weeks (offset * 7)
var lastDay = new Date(firstDay);
lastDay.setDate(lastDay.getDate() + 6);
// the last day is the first day plus 6
console.log(makeDateString(firstDay), makeDateString(lastDay));
range.innerHTML = 'week of ' + makeDateString(firstDay) + ' - ' + makeDateString(lastDay);
}
function makeDateString(date) {
var dd = date.getDate();
var mm = date.getMonth() + 1;
var y = date.getFullYear();
var dateString = mm + '/'+ dd + '/'+ y;
return dateString;
}
function backward() {
offset = offset - 1;
getWeek(offset);
}
function forward() {
offset = offset + 1;
getWeek(offset);
}
window.onload = function() {
getWeek();
}
在这里工作JSBin:http://jsbin.com/lawuyawoka/