2014-10-28 86 views
-1

如何在代碼中動態創建calendar()的多個函數?在jQuery中動態聲明函數

function calendar(){ 
    new JsDatePick({ 
    useMode:2, 
    target:'datepicker', 
    dateFormat:'%m-%d-%Y', 
    weekStartDay: 0 
    }); 

這裏是我的嘗試,我這麼近,我幾乎可以品嚐它:

$(function() { 
    $("[id^='datepicker']").each(function() { 
     var id = parseInt(this.id.replace("datepicker", "")); 

     function calendar+id(){ 
      new JsDatePick({ 
       useMode:2, 
       target:'datepicker'+id, 
       dateFormat:'%m-%d-%Y', 
       weekStartDay: 0 
      }); 
     } 
    }); 
}); 
+2

是否需要它?從我所看到的,你可以將'id'傳遞給函數'calendar'。 – 2014-10-28 20:33:35

回答

1

是否有需要多個功能。您可以通過id到下面的日曆功能,

$(function() { 
    $("[id^='datepicker']").each(function() { 
     calendar(parseInt(this.id.replace("datepicker", ""))); 
    }); 
    function calendar(id){ 
     new JsDatePick({ 
     useMode:2, 
     target:'datepicker'+id, 
     dateFormat:'%m-%d-%Y', 
     weekStartDay: 0 
     }); 
    } 
}); 
+0

這看起來像一個好主意,但似乎目標:'datepicker'+ id語法無效。它會返回datepickerundefined當我使用onmousedown ='日曆(2);' – theflarenet 2014-10-28 20:45:18

+1

@theflarenet問題是有點混亂,你有'onmousedown'處理程序的元素?如果是,那麼你不需要'.each',因爲你可以從'inline'調用'calendar(id)'。但是,如果您通過價值,我認爲這不會是不確定的。 http://jsfiddle.net/3cc4kqou/ – 2014-10-28 21:03:58

+0

我得到它的工作!非常感謝你! – theflarenet 2014-10-28 21:40:30