jquery datepicker - beforeShowDay problem

扶醉桌前 提交于 2019-12-11 09:27:11

问题


I have the following code:

$(document).ready(function(){

   $(".datepicker").each(function() {

     $(this).datepicker({
    beforeShowDay: function(date){ return [$(this).parent().find("span.days").html(), ""] },

     });
   });

  });

With this body code...

<div>
<span class="days">(date.getDay() == 1 || date.getDay() == 4)</span>
<input type="text" class="datepicker">
</div>


<div>
<span class="days">(date.getDay() == 2 || date.getDay() == 5)</span>
<input type="text" class="datepicker">
</div>

What I want to be able to do is have each datepicker have different days pickable.

The way i'm trying to do this (putting the varying part of the beforeShowDay code in a span) may not be the most elegant so feel free to take my code apart and change it if necessary.


回答1:


You could create an object keeping the pickable days, like this:

var pickable = { dp1: [1, 4], dp2: [2, 5] };
$('.datepicker').each(function() {
  $(this).datepicker({
    beforeShowDay: function(date){ 
        var day = date.getDay(), days = pickable[this.id];
        return [$.inArray(day, days) > -1, ""];
    }
  });
});​

You can give it a try here. The dp1 and dp2 are IDs of the controls..or any attribute you can map really, like this:

<input type="text" class="datepicker" id="dp1">
<input type="text" class="datepicker" id="dp2">

The concept is pretty simple, take the ID to get the array of days for this picker, then use $.inArray() to see if the day we're on is in that array. If these day selections may be shared, don't use an ID, instead do something like data-pickerType for the attribute, and replace this.id with $(this).attr("data-pickerType") in the code above.

Note: I left the .each() intact because I know you need it for reasons outside the current question.



来源:https://stackoverflow.com/questions/3812203/jquery-datepicker-beforeshowday-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!