在我的javascript代码下面。我想在输入已禁用标记中显示当前日期和时间。
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
HTML代码
<input type="textbox" name="inDate" id="indate" onload="this.value=getDateTime()" class="field left" disabled />
但它不起作用。给我一个解决方案。
答案 0 :(得分:0)
最简单的方法是使用ready
事件并在那里设置值
$(document).ready(function(){
$('#indate').val(getDateTime());
});
答案 1 :(得分:0)
您需要将值添加到Markup(即DOM)。你的功能不是这样做的,它只返回值并在内部存储它。
相反,尝试使用javascript添加HTML(将值作为新元素注入DOM)。 jQuery让它变得简单:
$(document).ready(function(){
$('#indate').val(getDateTime();
});
答案 2 :(得分:0)
HTML code:
<input type="textbox" name="inDate" id="indate" class="field left" disabled />
脚本: -
$(document).ready(function(){
$('#indate').val(getDateTime());
});
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}