2016-09-21 96 views
0

這裏這段JavaScript代碼是我的代碼:需要一些幫助,爲的DatePicker

$(function() { 
 
    $('#startDate').datepicker({ 
 
    dateFormat: "dd/mm/yy", 
 
    changeMonth: true, 
 
    changeYear: true, 
 
    showButtonPanel: true, 
 
    onClose: function(dateText, inst) { 
 

 

 
     function isDonePressed() { 
 
     return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1); 
 
     } 
 

 
     if (isDonePressed()) { 
 
     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)).trigger('change'); 
 

 
     $('.date-picker').focusout() 
 
     } 
 
    }, 
 
    beforeShow: function(input, inst) { 
 

 
     inst.dpDiv.addClass('month_year_datepicker') 
 

 
     if ((datestr = $(this).val()).length > 0) { 
 
     year = datestr.substring(datestr.length - 4, datestr.length); 
 
     month = datestr.substring(0, 2); 
 
     $(this).datepicker('option', 'defaultDate', new Date(year, month - 1, 1)); 
 
     $(this).datepicker('setDate', new Date(year, month - 1, 1)); 
 
     $(".ui-datepicker-calendar").hide(); 
 
     } 
 
    } 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css"> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script> 
 
<input id="startDate" />

問題是我不知道爲什麼日期更改爲年第一天,當我專注並回到它。如果您在代碼中發現錯誤,請告訴我。

jsfiddle

+0

在返回時不會改變 – depperm

+0

'$(this).datepicker('setDate',new Date(year,month-1,1));'in beforeShow是什麼原因造成的。 – ashok93

+0

把alert(datestr); alert(year);警報(月);在適當的地方,你會看到 –

回答

0

我找到幫助@depperm是在這部分的錯誤感謝

month = datestr.substring(0, 2); 

如果刪除了`beforeShow`一部分,那麼日期更正爲

month = datestr.substring(3, 5);