答案 0 :(得分:0)
你可以使用Date对象和一些jQuery来获得你之后的结果:http://jsfiddle.net/8cuL0k3h/
$(function() {
// Grab the date object and get hours/minutes
var current = new Date();
var hours = current.getHours();
var minutes = current.getMinutes();
// Check if time is before 10:30am
if( hours <= 10 && minutes < 30 ) {
$('#startend').val('Start');
}
// Check if time is after 2:30pm
else if( hours >= 14 && minutes > 30 ) {
$('#startend').val('End');
}
});
答案 1 :(得分:0)
如果您不反对PHP,可以检查当前时间并将其与您指定的时间进行比较。这必须包含在您正在处理的文件中,而不是您的操作文件。
<?php
// Set the default timezone so you don't run into timezone issues
// You can set this to whatever suits your application best
// Full list of supported timezones here: http://php.net/manual/en/timezones.php
date_default_timezone_set('America/Vancouver');
// Compare the current time to the start and end times
// This reads: if current time is before start time, option is selected, otherwise it's not
$start = (strtotime('now') < strtotime('10:30 AM today') ? 'selected="selected"' : '');
// This reads: if current time is after end time, option is selected, otherwise it's not
$end = (strtotime('now') > strtotime(' 2:30 PM today') ? 'selected="selected"' : '');
?>
要在您的选择控件中使用它,您可以在选项中回显变量(为简洁起见,以简写形式显示)。如果日期计算正确,将选择该选项,否则它将保持不变。我从占位符中删除了选择,因为此设置将确保始终选中“开始”或“结束”。
<select name="startfinish" id="startend" required>
<option disabled selection>Please select</option>
<option <?=$start?> value="Start">Start</option>
<option <?=$end?> value="End">End</option>
</select>
在这种情况下使用PHP的好处是它运行服务器端而不是客户端,因此您不必担心用户禁用Javascript并破坏您的表单设计。但是,如果您已经在应用程序中依赖jQuery,那可能不是问题。
答案 2 :(得分:0)
我假设网站是静态生成的,在这种情况下,PHP不会咬这个特定的苹果。这是一个只有JS的方法。
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
initSelectElement();
}
function makeItemSelected(listElem, index)
{
var i, n = listElem.options.length;
for (i=0; i<n; i++)
{
if (index == i)
listElem.options[i].setAttribute('selected','');
else
listElem.options[i].removeAttribute('selected');
}
}
function initSelectElement()
{
var curTime = new Date();
var curHour = curTime.getHours();
var curMin = curTime.getMinutes();
if ((curMin <= 30) && (curHour <= 10))
{
makeItemSelected(byId('startend'), 1);
}
else if ((curMin >= 30) && (curHour >= 2))
{
makeItemSelected(byId('startend'), 2);
}
}
</script>
<style>
</style>
</head>
<body>
<select name="startfinish" id="startend" required>
<option selected disabled>Please select</option>
<option value="Start">Start</option>
<option value="End">End</option>
</select>
</body>
</html>