2011-11-06 152 views
0

我正在使用帶Datepicker函數的jQuery UI插件來設置日期範圍。在其頁面上提供的示例(http://jqueryui.com/demos/datepicker/date-range.html)根據輸入'id'設置範圍;然而,我想設置基於'class'的範圍作爲我的表單'克隆'div來添加額外的輸入,使'id'字段在每個克隆上都是唯一的。當我將JavaScript更改爲使用'class'而不是'id'時,範圍不再起作用。jQuery UI Datepicker日期範圍

的JavaScript:

<script src="../../scripts/jquery-1.6.4.js"></script> 
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script> 
<script src="../../scripts/jqueryui/ui/jquery.ui.datepicker.js"></script> 
<script> 
     $(function() { 
      var dates = $(".start_date, .end_date").datepicker({ 
       onSelect: function(selectedDate) { 
        var option = this.class == "start_date" ? "minDate" : "maxDate", 
         instance = $(this).data("datepicker"), 
         date = $.datepicker.parseDate(
          instance.settings.dateFormat || 
          $.datepicker._defaults.dateFormat, 
          selectedDate, instance.settings); 
        dates.not(this).datepicker("option", option, date); 
       }  
      }); 
     }); 
</script> 

HTML:

<div> 
    <label> Start Date:</label> 
    <input type="text" name="start_date1" id="start_date1" class="start_date" /> 
</div> 
<div> 
    <label> End Date:</label> 
    <input type="text" name="end_date1" id="end_date1" class="end_date" /> 
</div> 
+0

您可能想詳細說明日期範圍「不再運作」的方式。是否有JavaScript錯誤?如果是這樣,哪些錯誤?他們做錯了什麼嗎?如果是這樣,怎麼樣? – Pointy

回答

0

要檢查,看看你的元素有一個類,這樣做:

if ($(this).is('.start_date')) { 

if ($(this).hasClass('start_date')) { 

DOM元素屬性的名稱是「className」,而不是「class」(令人困惑)。此外,它會讓你的代碼變得脆弱,以檢查類名是否等於某個字符串,因爲你永遠不知道是否需要添加另一個類(例如「required」)。因此,您應該始終使用jQuery或使用其他一些方法來檢查對象是否有多個類的可能性。

另外你可能想看看Filament Group的date range picker的jQuery。