[問題] 變數的生命週期

看板Flash作者 (潑潑)時間17年前 (2009/04/06 14:10), 編輯推噓1(1011)
留言12則, 4人參與, 最新討論串1/1
環境:flash mx pro 2004 var len; function creat(select) { len = xmlFood.firstChild.childNodes[select].childNodes.length; for (i=0; i<len; i++) { var t=xmlFood.firstChild.childNodes[select].childNodes[i].childNodes; img=xmlFood.firstChild.childNodes[select].childNodes[i].attributes.img; attachMovie("suba", "sub"+i, 100+i); this["sub"+i]._x = 0; this["sub"+i]._y = i*25; this["sub"+i].txt.text = t this["sub"+i].btn.onRelease = function() { _root.food.food_img.loadMovie(img);trace(img); }; } } -- this["sub"+i].btn 是子選的單按鈕 onRelease後會在food_img這個影片片段load從xml取得的圖片路徑 但在onRelease的function裡面我trace(img),都固定是最後一個 譬如: 現在len取得是6(0~5) this["sub"+i]也有指定到sub0~sub5 但loadMovie裡面的img卻是固定為childNodes[5]的值 //////////////////////////////////////////////////////////////////// 解: var len; function creat(select) { len = xmlFood.firstChild.childNodes[select].childNodes.length; for (i=0; i<len; i++) { var t =xmlFood.firstChild.childNodes[select].childNodes[i].childNodes; img =xmlFood.firstChild.childNodes[select].childNodes[i].attributes.img; attachMovie("suba", "sub"+i, 100+i); this["sub"+i]._x = 0; this["sub"+i]._y = i*25; this["sub"+i].txt.text = t; this["sub"+i].btn.img = img; this["sub"+i].btn.onRelease = function() { _root.food.food_img.loadMovie(this.img); }; } } -- 因為onRelease時 按下去的時候才去找i值,這個時候for早就跑完了,i當然維持在最終狀態 必須在迴圈裏面直接讓當時的i值跟MC(MovieClip)有關連 最快的方法 就是在MC身上插一個變數 this["mc" + i].i = i; 在onRelease裡面直接呼叫 this.i就好 這個i就不會是最終值 看精華區看不太懂,看上面cjcat2266這番話就懂了。 謝謝cjcat2266幫忙解答。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.170.22.136 ※ 編輯: Qiqi 來自: 118.170.22.136 (04/06 14:27) ※ 編輯: Qiqi 來自: 118.170.22.136 (04/06 14:27)

04/06 14:32, , 1F
請見精華區 3>7>3>1
04/06 14:32, 1F

04/06 14:32, , 2F
發生此狀況的理由跟解決方法都有講
04/06 14:32, 2F

04/06 14:33, , 3F
AS2沒有Dictionary,要嘛用用dynamic variable
04/06 14:33, 3F

04/06 14:34, , 4F
要嘛寫一個類似Dictionary的功能,一個物件對應一個值
04/06 14:34, 4F

04/06 14:34, , 5F
可以用 if (A == B) img = 3 這種方式來判斷
04/06 14:34, 5F

04/06 14:48, , 6F
請問,如何知道我用的是as2.0還是as3.0呢?
04/06 14:48, 6F

04/06 15:11, , 7F
新增檔案的時候應該就知道了
04/06 15:11, 7F

04/06 15:12, , 8F
而且有語法版本有差異,執行起來也會知道的
04/06 15:12, 8F

04/06 15:12, , 9F
1.屬性列設定高與寬那邊看的到 AS版本
04/06 15:12, 9F

04/06 15:12, , 10F
2.action工作列左上角有
04/06 15:12, 10F

04/06 15:12, , 11F
3.發佈設定的flash裡面也有
04/06 15:12, 11F

04/06 15:23, , 12F
了解 原文跟推文的問題都解決了,謝謝大家
04/06 15:23, 12F
※ 編輯: Qiqi 來自: 118.170.22.136 (04/06 15:30)
文章代碼(AID): #19sPpdTg (Flash)