Re: [問題] javascript for迴圈

看板Web_Design作者 (沉默是金。)時間13年前 (2011/05/29 19:13), 編輯推噓0(005)
留言5則, 3人參與, 最新討論串2/2 (看更多)
※ 引述《apiod ( )》之銘言: : 以下是原始程式碼 : var dates = $("#test_CHECKDATESTART, #test_CHECKDATEEND").datepicker({ : defaultDate: "+1w", : changeMonth: false, : numberOfMonths: 1, : onSelect: function (selectedDate) { : var option = this.id == "test_CHECKDATESTART" ? "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); : } : }); 你這裡如果只是想躲 dates ,i 會在迴圈中被換掉的這件事, 可以繞條路作 for example (function(dates, index){ dates.datepicker({ defaultDate: "+1w", changeMonth: false, numberOfMonths: 1, onSelect: function (selectedDate) { var option = this.id == "test"+index+"_CHECKDATESTART" ? "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); } }); })($("#test"+i+"_CHECKDATESTART, #test"+i+"_CHECKDATEEND"),i); 回完想想才發現dates 不是重點,重點應該是 i , 所以程式碼有點多餘,不過這範例應該意思到了。:-| 至於為什麼這樣跟原本的寫法會有差,因為這裡dates,index 不會被改掉。 (他就是parameter,只存在這個function的空間裡。) 我記得我之前寫過一篇文章講過 closure ...要翻翻 : var dates = $("#test_CHECKDATESTART, #test_CHECKDATEEND").datepicker({ : defaultDate: "+1w", : changeMonth: false, : numberOfMonths: 1, : onSelect: function (selectedDate) { : var option = this.id == "test_CHECKDATESTART" ? "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); : } : }); : 我想改用for迴圈讓它變這樣 : for(i=1;i<=3;i++) : { : var dates1 = $("#test1_CHECKDATESTART, #test1_CHECKDATEEND").DATEPICKER( : ........... : var option = this.id == "test1_CHECKDATESTART" ? "minDate" : "maxDate", : .......... : dates1.not(this).datepicker("option", option, date); : }); : var dates2 ..... : var dates3 ..... : } : 請問有辦法做到嗎? : 我在dates和test後面加i也不行 : 請問該如何修改呢? : thx -- I am a person, and I am always thinking . Thinking in love , Thinking in life , Thinking in why , Thinking in worth. I can't believe any of what , I am just thinking then thinking , but worst of all , most of mine is thinking not actioning... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 42.72.242.73

05/29 19:20, , 1F
可以看 ajax板的這兩篇 #18vQOwa6 (Ajax) #191ecDKo (Ajax
05/29 19:20, 1F
※ 編輯: TonyQ 來自: 42.72.242.73 (05/29 19:23)

05/29 19:23, , 2F
如果使用者之後還需要對dates1 dates2作處理,
05/29 19:23, 2F

05/29 19:23, , 3F
拿個object塞key進去存就是了...
05/29 19:23, 3F

05/29 19:43, , 4F
thank you~:)
05/29 19:43, 4F

05/29 20:08, , 5F
好複雜@@"
05/29 20:08, 5F
文章代碼(AID): #1DuYfn7F (Web_Design)
討論串 (同標題文章)
文章代碼(AID): #1DuYfn7F (Web_Design)