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

How to change jquery datepicker style dynamically

我正在努力使用动态更改样式的 jquery 日期选择器。我想要做的是,如果单击复选框,则日期选择器仅显示年份和月份,否则,日期选择器将正常使用年月日。

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

如果有人知道问题出在哪里,请帮助我。那太好了,谢谢。

=====编辑=====

根据 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();
    });
  }
}