我是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-04-11 15:14:31
正确:
var dateDict = {
"2021-04-01": 1,
"2021-04-02": 1,
"2021-04-03": 5,
"2021-04-04": 1,
"2021-04-05": 2
};此外,我在datePicker中发现的一个错误是,如果您先选择to日期,然后再选择from日期,那么实际上您可能会搞乱逻辑,因为现在to日期可以在from日期之前。
<!-- 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').val(""); // RESET toDate when fromDate is changed
$('#toDate').prop('min', function(){
return fromDate;
})
});
</script>
<!-- Storing the Value of the fromDate and toDate -->
<script>
var dateDict = {
"2021-04-01": 1,
"2021-04-02": 1,
"2021-04-03": 5,
"2021-04-04": 1,
"2021-04-05": 2
};
function myFunction() {
var x = document.getElementById("fromDate").value;
var y = document.getElementById("toDate").value;
document.getElementById("selectedDate").innerHTML = x + y;
console.log(fromDate in dateDict); // gives true if fromDate is in dateDict
console.log(dateDict[fromDate]); // gives the value corresponding to the date
}
</script>
https://stackoverflow.com/questions/67041385
复制相似问题