【问题标题】:I hate this repetition, but how can I fix it- jquery, bootstrap 4 datepicker我讨厌这种重复,但我该如何解决它-jquery,bootstrap 4 datepicker
【发布时间】:2021-08-10 14:35:51
【问题描述】:

我想在两个不同的字段上使用 datepicker,但是每个字段都有不同的属性,我不希望代码重复,通过查看我的第一个和第二个代码 sn-p,你会明白我想要什么。

// first code snippet give unexpected result, when user change the first field then the second one do the change on the info block, this means that the change function get fired and affect all field at once
$('#first, #second').datepicker({
    format: 'dd/mm/yyyy',
    autoclose: true
}).on("change", function () {
   $(".first-info").remove();
   $(".second-info").remove();
});

我的第二个代码给出了想要的结果,但是如何避免 datepicker 上的重复。

//first field
$('#first').datepicker({
     format: 'dd/mm/yyyy',
     autoclose: true
 }).on("change", function () {
    $(".first-info").remove();
 });
 //second field
 $('#second').datepicker({
    format: 'dd/mm/yyyy',
    autoclose: true
}).on("change", function () {
   $(".second-info").remove();
});

【问题讨论】:

    标签: jquery datepicker


    【解决方案1】:

    在所有日期选择器字段上放置一个公共类,然后在它们上使用data 属性来指定要删除的关系。像这样的:

    <input type="text" class="datepicker" data-relation=".first-info" />
    <input type="text" class="datepicker" data-relation=".second-info" />
    
    $('.datepicker').datepicker({
      format: 'dd/mm/yyyy',
      autoclose: true
    }).on("change", function() {
      let selector = $(this).data('relation');
      $(selector).remove();
    });
    

    请注意,如果您可以使用 DOM 结构和 jQuery 的遍历方法(例如 closest()、find()、next() 等)关联元素,也可以避免使用 data 属性。

    【讨论】:

    • @marc_s,你能解释一下为什么当我将日期更改为 01/12/2039 时它返回 01/01/1970
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    相关资源
    最近更新 更多