2012-01-04 34 views

回答

4

我喜歡使用jQuery UI's datepicker(),因爲我通常都會加載jQuery UI,而且它是相當知名/受支持的。

不幸的是,日期選擇器功能使用了一些犯錯的事件代碼,這需要在沙盒環境中工作一點。

不過,它並不太難。下面是一個完整的Greasemonkey腳本:

// ==UserScript== 
// @name  _Datepicker fun 
// @include  http://YOUR_SERVER/YOUR_PATH/* 
// @include  http://jsbin.com/ukelij* 
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js 
// @require  https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js 
// @resource jqUI_CSS http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css 
// ==/UserScript== 

//--- Date picker needs additional CSS 
GM_addStyle (GM_getResourceText ("jqUI_CSS")); 

//--- Add datepicker popups to select inputs: 
$("#pickMe").datepicker(); 
$("#pickMe").click (function() { 
    setTimeout (cleanUpCrappyEventHandling, 100); 
}); 

/*--- Clean up ultra-crappy event handling ('til dev team eventually fixes). 
    This must be done to allow the picker to work in a sandboxed environment. 
    Alternately, you can modify the jQuery-UI source ala http://stackoverflow.com/q/2855403 
*/ 
function cleanUpCrappyEventHandling() { 
    var nodesWithBadEvents = $(
     "div.ui-datepicker td[onclick^='DP'], div.ui-datepicker a[onclick^='DP']" 
    ); 
    nodesWithBadEvents.each (function() { 
     var jThis  = $(this); 
     var fubarFunc = jThis.attr ("onclick"); 

     /*--- fubarFunc will typically be like: 
      DP_jQuery_1325718069430.datepicker._selectDay('#pickMe',0,2012, this);return false; 
     */ 
     fubarFunc  = fubarFunc.replace (/return\s+\w+;/i, ""); 

     jThis.removeAttr ("onclick"); 
     jThis.click (function() { 
      eval (fubarFunc); 
      cleanUpCrappyEventHandling(); 
     }); 
    }); 
} 


可以加載此並測試它反對this page at jsBin

+0

感謝您分享這個令人敬畏的代碼,但它不適合我。運行JavaScript控制檯我看到這個錯誤「GM_getResourceText未定義」 – user390480 2012-01-05 14:09:10

+0

您正在使用Firefox和Greasemonkey,對不對?你是否試圖直接在控制檯中運行這些代碼? 'GM_getResourceText'只能在FF,GM腳本中使用,或者在運行Chrome時使用* Tampermonkey *。 – 2012-01-05 19:45:15

相關問題