Re: [問題] javascript for迴圈
※ 引述《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
05/29 19:20, 1F
※ 編輯: TonyQ 來自: 42.72.242.73 (05/29 19:23)
→
05/29 19:23, , 2F
05/29 19:23, 2F
→
05/29 19:23, , 3F
05/29 19:23, 3F
→
05/29 19:43, , 4F
05/29 19:43, 4F
→
05/29 20:08, , 5F
05/29 20:08, 5F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):