var today = new Date();
var dd = today.getDate();
var mm=today.getMonth();
mm++;
var yyyy =today.getFullYear();
// alert(mm);
var datee=yyyy+'-'+mm+'-'+dd;
$('#form_date').val(datee);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='date' id='form_date'>
我只需要在输入类型日期中自动选择当前日期,就可以从get函数中获取年,月和日,但是当我尝试将它们赋值时,它是行不通的
答案 0 :(得分:2)
此代码无法正常运行,因为它在运行时找不到正确的dom元素。因此,将代码包装在$(document).ready(function(){})
函数中。
答案 1 :(得分:2)
单数月和日应以零开头:
//<![CDATA[
/* external.js */
function makeFormDate(dateInstance){
var dt = dateInstance instanceof Date ? dateInstance : new Date;
return dt.getFullYear()+'-'+(dt.getMonth()+1).toString().replace(/^(\d)$/, '0$1')+'-'+dt.getDate().toString().replace(/^(\d)$/, '0$1');
}
$(function(){
$('#form_date').val(makeFormDate());
});
//]]>
<script src=''></script>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<input id='form_date' type='date' value='' />
</body>
</html>