以下是旁邊的原代碼,以幫助解釋了什麼是可能發生的一些意見:
function setupButtons():void {
//you're adding a click listener for every object in `buttons`
for (var obj:Object in buttons)
{
buttons[obj].addEventListener(MouseEvent.CLICK, checkAnswer);
}
//this next line seems out of place,
//it is NOT a part of your for loop above so it will only run once,
//The value of obj will be the LAST item in the for loop above
buttons[obj].addEventListener(MouseEvent.MOUSE_UP,disableBtns);
}
function disableBtns(evt:MouseEvent):void {
//you don't have curly braces on this next for loop line
//this means it's only going to run the line immediately following the loop as part of the loop.
for (var obj:Object in buttons)
//your attempting to remove the same listener over and over again (since this line is in a loop)
evt.currentTarget.removeEventListener(MouseEvent.MOUSE_UP,disableBtns);
//this next line is not part of the loop above.
//I imagine you only want to disable the button that was clicked (evt.currentTarget)
//This will only disable whatever the last value of obj was in the loop above
buttons[obj].enabled = false;
}
現在,這裏是一個簡單的代碼重構,可以幫助:
//first, just have one click listener for each button, forget the mouse up listener
function setupButtons():void {
for (var obj:Object in buttons){
buttons[obj].addEventListener(MouseEvent.CLICK, btnClick);
}
}
function btnClick(evt:MouseEvent):void {
//If buttons are of the SimpleButton class, you can just disable them
evt.currentTarget.enabled = false;
//OR, if the buttons are not of the SimpleButton class
evt.currentTarget.mouseChildren = false;
evt.currentTarget.mouseEnabled = false;
//OR, just remove the click listener
evt.currentTarget.removeEventListener(MouseEvent.CLICK, btnClick);
//run the checkAnswer function
checkAnswer(evt);
}
要禁用所有按鈕whe ñ任何1被點擊,你可以這樣做:
function btnClick(evt:MouseEvent):void {
for (var obj:Object in buttons){
buttons[obj].removeEventListener(MouseEvent.CLICK, btnClick);
}
//run the checkAnswer function
checkAnswer(evt);
}
謝謝你的答案。這當然更清潔,更合乎邏輯。不過,我嘗試過,但它仍然不禁用按鈕。我可以多次點擊它並每次不斷增加分數(checkAnswer函數 – Don
我編輯了答案以顯示其他一些可以嘗試禁用'btnClick'函數中的按鈕的功能。取出已啓用如果嘗試使用其中一種, – BadFeelingAboutThis
再次感謝我的朋友,我試過了你給的兩個選項,他們的工作 – Don