如何动态改变jquery日期选择器样式

How to change jquery datepicker style dynamically

本文关键字:jquery 日期 选择器 样式 改变 何动态 动态      更新时间:2023-09-26

我正在与动态更改样式的jquery日期拾取器作斗争。我想做的是,如果复选框被点击,那么日期选择器只显示年和月,如果没有,日期选择器正常工作与年,月和日期。

我写了下面的脚本。我可以看到下面的脚本被触发,并没有显示任何问题,但它没有工作。

如果有人知道是什么问题,请帮助我。那太好了,谢谢。

===== edit =====

根据Barmar的建议,我可以动态地改变dateFormat。但我仍然无法切换显示日期选择器的日历部分我正在尝试$(".ui-datepicker-calendar").css({ "display": "none" });$(".ui-datepicker-calendar").css({ "display": "inline-block" });

有人知道这个问题的解决方案吗?

function addEventCheckBox() {
    $("#checkBoxForFlag").live("click", function(e) {
        changeDatePicker();
    });
}
function changeDatePicker() {
    var flag = $("#checkBoxForFlag").is(":checked");
    if (flag) {
        $("#testDate").datepicker("option", {
            dateFormat: "yy/mm"
        });
        $(".ui-datepicker-calendar").css({ "display": "none" });
    } else {
        $("#testDate").datepicker("option", {
            dateFormat: 'yy/mm/dd',
        });
        $(".ui-datepicker-calendar").css({ "display": "inline-block" });
    }
}

.datepicker(<options>)函数只能用于初始化一个新的日期选择器。要更改现有的日期选择器,请使用option方法。你可以给出一个包含你要修改的选项的对象,也可以只给出一个选项作为一个参数。

function changeDatePicker() {
    var flag = $("#checkBoxForFlag").is(":checked");
    if (flag) {
        $("#testDate").datepicker("option", "dateFormat", "yy/mm");
        $(".ui-datepicker-calendar").hide();
    } else {
        $("#testDate").datepicker("option", "dateFormat", "yy/mm/dd");
        $(".ui-datepicker-calendar").show();
    }
}

经过一些实验尝试,我解决了这个问题。所以我把解决方案写在这里,给那些可能有同样问题的人。

function changeDatePicker() {
  var flag = $("#checkBoxForFlag").is(":checked");
  if (flag) {
    $("#testDate").datepicker("destroy");
    $("#testDate").datepicker({
      showOn: "both",
      buttonImageOnly: false,
      dateFormat: "yy/mm",
      changeMonth: true,
      changeYear: true,
      maxDate: 0,
      buttonText: "",
      onClose: function () {
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));
      }
    });
  $("#testDate").focus(function () {
    $(".ui-datepicker-calendar").hide();
    $("#ui-datepicker-div").position({
        my: "center top",
        at: "center bottom",
        of: $(this)
    });
  });
  $("#testDate").blur(function () {
    $(".ui-datepicker-calendar").hide();
  });
  } else {
    $("#testDate").datepicker("destroy");
    $("#testDate").datepicker({
      showOn: "both",
      buttonImageOnly: false,
      dateFormat: userDateFormat_datepicker,
      changeMonth: true,
      changeYear: true,
      showButtonPanel: true,
      maxDate: 0,
      buttonText: ""
    });
    $("#testDate").focus(function () {
      $(".ui-datepicker-calendar").show();
    });
    $("#testDate").blur(function () {
      $(".ui-datepicker-calendar").show();
    });
  }
}