【发布时间】:2021-04-11 04:10:30
【问题描述】:
我是 Javascript、html 和 css 的新手。任何帮助将不胜感激 :) 我有一个日历,您可以在其中选择日期范围。我希望有这个范围来根据日期过滤掉字典。
我已经创建了日历和字典。这是我的 HTML 中的日历代码和字典代码。
我尝试使用 console.log() 进行调试。正如您在此处看到的,dateDict 和 fromDate 中的键具有相同的格式和数据类型,但 dateDict 不将 fromDate 识别为 dateDict 中的键之一。那么如何根据日历中的选定范围从字典中获取值
<!-- Block for the Calendar -->
<div class="calendar">
<label>From Date</label>
<input type="date" name="" max="" id="fromDate">
<br><br>
<label>To Date</label>
<input type="date" name="" max="" id="toDate">
<br><br>
<button onclick="myFunction()">See Data</button>
</div>
<p id="selectedDate"></p>
<!-- Block for Calendar to show error-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
var fromDate;
$('#fromDate').on('change', function(){
fromDate = $(this).val();
$('#toDate').prop('min', function(){
return fromDate;
})
});
</script>
<!-- Storing the Value of the fromDate and toDate -->
<script>
var dateDict = {
"2021-4-1": 1,
"2021-4-2": 1,
"2021-4-3": 5,
"2021-4-4": 1,
"2021-4-5": 2
};
console.log(dateDict);
console.log(typeof dateDict);
function myFunction() {
var x = document.getElementById("fromDate").value;
var y = document.getElementById("toDate").value;
document.getElementById("selectedDate").innerHTML = x + y;
console.log(x);
console.log(typeof x); // x is a string
console.log(fromDate);
console.log(typeof fromDate); // is also a string
console.log(fromDate in dateDict); //but gives false, when both have the same format and data type
}
</script>
【问题讨论】:
-
2021-4-1与2021-04-01不是同一个字符串,fromDate in dateDict也比较值,而不仅仅是类型。 -
您好,非常感谢您的回复。我编辑了 dateDict 键,到目前为止它可以工作! :) 我不确定如何将您的答案标记为已接受的答案
-
不客气,你不能这样做,因为这不是一个答案,它是一个评论,因为这是你需要的一个小改动,我认为一个评论就足够了 :)
-
您好,对不起,实际上我面临另一个问题,即当我尝试从键中查找值时,我得到的是未定义而不是值。 e.i console.log(dateDict[fromDate]) 显示未定义。 .. 嗯.. 知道为什么当我检查 console.log(fromDate in dateDict) 显示为真时会发生这种情况吗?
标签: javascript html calendar range