我需要有关JS和html的帮助。我需要将<input type = "date" id = "date">
存储在JS var中。如果您尝试将日期存储在简单的var中,并尝试打印它而不是选择的日期,则会显示“ undefined”:
$("#printDate").click(function(){
var dateVar = ($("#date").val());
$("#results").append("<p>" + dateVar + "</p>")
});
如果您尝试使用dateVar
将日期存储在new Date()
中,则会显示“无效日期”:
$("#printDate").click(function(){
var dateVar = new Date($("#date").val());
$("#results").append("<p>" + dateVar + "</p>")
});
感谢您的任何帮助!
upd:整页代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
`<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">`</script>
</head>
<body>
<div id="results"></div>
<input type="date" id = "dateInput">
<button id = "printDate">PrintDate</button>
<script>
$("#printDate").click(function(){
var dateVar = new Date($("#date").val());
$("#results").append("<p>" + dateVar + "</p>")
});
</script>
</body>
</html>
答案 0 :(得分:1)
$("#printDate").click(function(){
var dateVar = new Date($("#dateInput").val());
$("#results").append("<p>" + dateVar + "</p>")
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">`</script>
</head>
<body>
<div id="results"></div>
<input type="date" id = "dateInput">
<button id = "printDate">PrintDate</button>
</body>
</html>
您的代码唯一的问题是您定位了错误的ID,即$("#date")
而不是$("#dateInput")
答案 1 :(得分:0)
<div id="results"></div> <input type="date" id="dateInput"> <button id="printDate">PrintDate</button> <script> $("#printDate").click(function(){ var dateVar = new Date($("#dateInput").val()); $("#results").append("<p>" + dateVar + "</p>") }); </script>
您输入错误。