使用beforeShow()在datepicker中添加类

时间:2017-04-20 07:59:32

标签: javascript jquery css jquery-ui datepicker

我尝试使用此功能在所选日期元素上添加一个类:

function ValidateHidePrivate() { // rest of code }

我有两个问题。首先,没有增加这样的课程。其次,日志显示了一种奇怪的行为。我打开datePicker的前两次,beforeShow:function(){ $(".ui-datepicker-current-day").addClass('testX') }返回false,但第三次显示为true(而hasClass()类仍未在html中显示)。



testX

 $(function() {
  $( "#datepicker" ).datepicker({
    beforeShow:function(){     
      console.log('================================================');
      console.log($( ".ui-datepicker-current-day" ).hasClass('testX'));
      $( ".ui-datepicker-current-day" ).addClass('testX');
      console.log($( ".ui-datepicker-current-day" ).hasClass('testX'));
    }
  });
});

.container {
  width: 600px;
  padding: 20px;
  margin: auto;
  background: #ddd;
}
.testX{
  background-color:red;
}




2 个答案:

答案 0 :(得分:2)

$("#datepicker").datepicker({
            afterShow: function () {
                console.log('================================================');
                console.log($(".ui-datepicker-current-day").hasClass('testX'));
                $(".ui-datepicker-current-day").addClass('testX');
                console.log($(".ui-datepicker-current-day").hasClass('testX'));
            }
        });

以上代码已更新,您可以在#datetimepicker上使用onfous事件。 以下给出的代码可能对您有所帮助。它对我有用。

  $(function () {

       $("#datepicker").focus(function(){
              console.log('================================================');
                console.log($(".ui-datepicker-current-day").hasClass('testX'));
                $(".ui-datepicker-current-day").addClass('testX');
                console.log($(".ui-datepicker-current-day").hasClass('testX'));

         });

    });

答案 1 :(得分:2)

试用此代码

var selectedDay = new Date().getDate();
$(function() {
    $( "#datepicker" ).datepicker({
        onSelect: function(dateText, inst) {
            selectedDay = inst.selectedDay;
        },
        beforeShowDay: function (date) {
            if (date.getDate() == selectedDay && !$('#datepicker').val()=="") {
                return [true, "testX", ""]; 
            } else {
                return [true, ""]
            }
        }
    });
});
.container {
  width: 600px;
  padding: 20px;
  margin: auto;
  background: #ddd;
}
.testX{
  background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<link href="//code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<div class="container">
  <p>This is a datepicker example using jquery, jquery ui, and jquery css</p>
<form>
Date:
<input id="datepicker">
</form>
</div>

希望这有帮助