我有3个html <select>
年,月和日。年和月都自动设置为当前年和当月。我纯粹是用PHP做的。然而,即使我已经做了
if (j == <?php echo date('d') ?>) days_select.options[days_select.options.length] = new Option(j, j, true);
默认日期仍然是1而不是当天。甚至令人沮丧的是,当我在萤火虫上检查时,选定的日子是当天...我在编程中总是一个菜鸟,这就是为什么这些简单的东西对我来说很难掌握。请帮忙......
date_select.php
<body onload="loadDays();">
<script type="text/javascript" >
function loadDays() {
var year = parseInt(document.getElementById('years').value);
var month = document.getElementById('months').value;
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var days = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
if ((year % 4) == 0) days[1] = 29;
var days_select = document.getElementById('days');
days_select.options.length = 0;
for(i in months) {
if (month == months[i]) {
for(var j = 1; j <= days[i]; j++ ) {
if (j == <?php echo date('d') ?>) days_select.options[days_select.options.length] = new Option(j, j, true);
else days_select.options[days_select.options.length] = new Option(j, j);
}
break;
}
}
}
</script>
<span style="display: table; ">
<span style="display: table-cell; ">
<select id="years" onchange="loadDays();">
<?php
for($year = 1900; $year <= 2100; $year++ ) {
if ($year == date('Y')) echo "<option value='$year' selected=''>" . $year . "</option>";
else echo "<option value='$year'>" . $year . "</option>";
}
?>
</select>
</span>
<span style="display: table-cell; ">
<select id="months" onchange="loadDays();">
<?php
$months = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" );
foreach($months as $month){
if ($month == date('M')) echo "<option value='$month' selected=''> " . $month . "</option>";
else echo "<option value='$month'> " . $month . "</option>";
}
?>
</select>
</span>
<span style="display: table-cell; ">
<select id="days" >
</select>
</span>
</span>
</body>
答案 0 :(得分:1)
我认为可能是因为<?php echo date('d') ?>
生成带有前导零的字符串"04"
。您的j
循环计数器是一个整数,并且永远不会匹配PHP输出的字符串。
尝试将其包装在Javascript的parseInt()
函数中,或使用date('j')
表示没有前导零。
if (j == parseInt(<?php echo date('d') ?>))
更好的是,只需使用Javascript自己的Date对象来获取当天。
var theDateObj = new Date();
var today = theDateObj.getDate(); // Will output int 4 for today.
答案 1 :(得分:1)
我把它作为一个单独的答案,因为它是一个。
Option()
的第三个参数是默认选择该选项,就好像它是在HTML中指定的那样。第四是现在是否真的被选中。在您的true
电话中添加另一个Option()
,这对我来说非常有用。
new Option(j, j, true, true)