显示从datepicker触发的图像

时间:2018-03-08 16:28:33

标签: javascript jquery datepicker

我有一个图像目录,我想根据datepicker jquery日历的输入显示。图像的文件名格式为:YYMMDD_file.png。例如,180303_image.png

我希望显示当天的正确图像,通过点击相应的jquery日历(https://jqueryui.com/datepicker/)触发,范围仅为前3个月。对于datepicker,我到目前为止已经有了jquery和html:

<script type="text/javascript">
jQuery(function() {     
    var date = new Date();
    var currentMonth = date.getMonth();
    var currentDate = date.getDate();
    var currentYear = date.getFullYear();

    $('#calendar123').datepicker({
        minDate: new Date(currentYear, currentMonth-3, currentDate),
        maxDate: new Date(currentYear, currentMonth, currentDate)
    });
});</script>
<div style="font-weight: bold;">Previous 3 months</div>
<div id="calendar123"></div>

如何从datepicker中选择日期并显示我的相应图像?

1 个答案:

答案 0 :(得分:2)

您可以使用onSelect中的datepicker通知获取当前所选日期:

<script type="text/javascript">
        jQuery(function () {
            var date = new Date();
            var currentMonth = date.getMonth();
            var currentDate = date.getDate();
            var currentYear = date.getFullYear();
            //Set the relative path to the images folder.
            var imagePath = "../images/";

            $('#calendar123').datepicker({
                minDate: new Date(currentYear, currentMonth - 3, currentDate),
                maxDate: new Date(currentYear, currentMonth, currentDate),
                onSelect: function (theDate) {
                    // Convert the date string to a Date
                    var selectedDate = new Date(theDate);
                    var imageName = "";
                    var year = selectedDate.getFullYear().toString().slice(-2); // Get last two digits.
                    var month = ("0" + (selectedDate.getMonth() + 1)).slice(-2); // Added 1 as the month value is zero indexed.
                    var day = ("0" + selectedDate.getDate()).slice(-2);
                    imageName = year + month + day + "_image.png";    
                    $("#myImage").attr('src', imagePath + imageName);
                }
            });
        });</script>

    <div style="font-weight: bold;">Previous 3 months</div>
    <div id="calendar123"></div>
    <img id="myImage">