带有JQueryUI DatePicker的问题

问题描述 投票:0回答:1

我在使用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">

jquery jquery-ui jquery-ui-datepicker
1个回答
0
投票
您可以简单地使用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>
© www.soinside.com 2019 - 2024. All rights reserved.