首页 > 解决方案 > JQueryUI DatePicker 的问题

问题描述

我在使用 JQueryUI DatePicker 循环遍历具有类的一组元素时遇到问题,我似乎无法弄清楚我的问题出在哪里,因为控制台只是告诉我一个不应该未定义的元素是未定义的。


$(document).ready(function () {
        $('.date').toArray().forEach(function (field) {

            $(field).datepicker({
                showOn: '',
                dateFormat: 'yy-mm-dd',
                changeMonth: true,
                changeYear: true,
                yearRange: "c-100:c+100",
                beforeShow: function () {
                    setTimeout(function () {
                        $(field).css('z-index', 999999);
                    }, 0);
                }
            });

            let class_to_use = '.'+$(field).attr('id');

            let icon = $(class_to_use);
            console.log(icon); // fine, not undefined, it is the correct element
            icon.click(function () {
                console.log('clicked'); 
                $(field).datepicker("show")
                // but on click I get...
                // Uncaught TypeError: Cannot read property 'left' of undefined
             });
        });

    });

如果这很重要,这个输入是模态的,我做错了什么?

这是为其中一个元素呈现的 HTML,有多个元素,这就是我要循环的原因:

<i class="id_date fa fa-calendar-alt prefix prefix-smaller form-icon-adjust" style="cursor: pointer; color: var(--sidebar-bg-color)"></i>
<div class="md-form form-icon-margin ">

<input type="text" name="date" class="form-control date" required id="id_date">

标签: jqueryjquery-uijquery-ui-datepicker

解决方案


您可以简单地使用该button选项并设置按钮样式来满足您的需求。您不必为自己的参与而战。

$(function() {
  $('.date').each(function(i, el) {
    var field = $(el);
    $(field).datepicker({
      showOn: 'button',
      dateFormat: 'yy-mm-dd',
      changeMonth: true,
      changeYear: true,
      yearRange: "c-100:c+100"
    });
    var btn = field.next("button");
    var icon = $("<i>", {
      class: "fa fa-calendar-alt"
    });
    btn.addClass("id_date prefix prefix-smaller form-icon-adjust").css({
      cursor: "pointer",
      color: "var(--sidebar-bg-color)"
    }).html(icon);
  });
});
.date-control .id_date {
  float: left;
  width: 30px;
  height: 32px;
  margin: 1px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="md-form form-icon-margin date-control">
  <input type="text" name="date" class="date" required id="id_date">
</div>


推荐阅读