我正在使用Jquery datepicker元素,该元素仅允许用户选择月份。

<style>
    .ui-datepicker-calendar {
        display: none;
    }
</style>


上面的css工作正常。但是我传递了一个变量,该变量指示用户是只能选择月份还是可以选择日期。一种条件样式。

现在,代码对我来说就像这样。

<head>
    <link rel="stylesheet" href="styles/jquery-ui.css" />
    <script language="javascript" type="text/javascript" src="js/jquery.js" ></script>
    <script language="javascript" type="text/javascript" src="js/jquery-ui.js"></script>
</head>

//some code here

 <label for="myDate">myDate</label>
 <input type="text" id="myDate" name="myDate" />

//some more code

if(//myTest - This is to test if only months are to be shown)
    {
        $(".ui-datepicker-calendar").css("display", "none");

            $('#myDate').datepicker( {
                changeMonth: true,
                changeYear: true,
                changeDate: false, // This parameter is just for trial. On cross-checking with jquery-ui.js, I found there's no such property. :(
                showButtonPanel: true,
                dateFormat: 'MM yy',
            });

        //$(".ui-datepicker-calendar").css({display: 'none'}); -- This didn't work either
    }
    else
    {
        //normal code for a jquery datepicker
    }

});


现在,上面的代码没有给我所需的输出。我需要执行:

$(".ui-datepicker-calendar").css("display", "none");


仅当以上代码中的myTest为true时。

换句话说,它仍在日期选择器中显示我不想显示的日期。

请帮忙。

最佳答案

尝试这个:

function handleDateInput() {

  var $input = $('#myDate');
  var dClass = "ui-normal";

  var dOptions = {
    changeMonth: false,
    changeYear: false,
    dateFormat: 'dd MM yy',
    showButtonPanel: false
  };

  if( $input.data('month-only') === true ) {

    var dFormat = "MM yy";

    dOptions = {
      changeMonth: true,
      changeYear: true,
      showButtonPanel: true,
      dateFormat: dFormat,
      onClose: function( e, ui ) {
        var d = new Date( ui.drawYear , ui.drawMonth , 1);
        $(ui.input).datepicker('setDate', d);
      }
    };

    dClass = "ui-month-only";

  }

  $('#myDate').datepicker( dOptions ).datepicker('widget').addClass( dClass );

};

// these next 2 lines can be run whenever you need
$('#myDate').data('month-only', true);
handleDateInput();


CSS中的.ui-month-only .ui-datepicker-calendar { display: none; }
这是它的一个JSFIDDLE:http://jsfiddle.net/FgwwT/3/

根据逻辑更改数据选项时,调用handleDateInput()函数。

我认为这是您想要实现的目标,希望对您有所帮助! :)

关于jquery - jQuery DatePicker条件样式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18102466/

10-12 00:09
查看更多