2011-05-27 49 views
0

這是4個按鈕我有我下面的網頁是代碼:環路我點擊按鈕在JavaScript

<div id ="topbar" width="80%; height:20px;" style="text-align:center"> 
    <input type="button" value="Click first" onclick="button.toggle();"></input> 
    <input type="button" value="Click second" onclick="button2.toggle();"></input> 
    <input type="button" value="Click third" onclick="button3.toggle();"></input> 
    <input type="button" value="Click fourth" onclick="button4.toggle();"></input> 
</div> 

頁面加載時,目前,所有的人都是「開」(切換不開或關) 如何把它們全部關閉,然後循環他們是這樣的:

1上休息關閉
2上休息關閉
3休息關閉
4上休息休息關閉
1 O ff ....並且它保持循環。

我試過這種方法
這是怎麼回事?

setInterval ("loop()", 2000); 

function loop () 
{ 
setTimeout ("SetLayer1()", 1000); 
} 

function SetLayer1() 
{ 
button.toggle(); //all off since all of them are on from start 
button2.toggle(); 
button3.toggle(); 
button4.toggle(); 
} 
function SetLayer2() 

button.toggle(); // button 1 on rest off 
//button2.toggle(); 
//button3.toggle(); 
//button4.toggle(); 
} 
function SetLayer3() 
{ 
button.toggle(); // button 1 off 
button2.toggle(); //button 2 on 
//button3.toggle(); 
//button4.toggle(); 
} 
function SetLayer4() 
{ 
//button.toggle(); 
button2.toggle();// button 2 off 
button3.toggle();// button 3 on 
//button4.toggle(); 
} 
+0

您需要發佈的代碼。 – 2011-05-27 02:55:03

+0

是啊,它不那麼容易...... :)我正在嘗試縮進..... 4空格 – Ossi 2011-05-27 02:59:45

回答

0

這是基本的,沃森。遞歸。一個示例實現可以是這樣的:

使一個變量保存所有的按鈕和另一個變量index(或類似的東西)。然後,創建一個函數。

在那個函數裏面,你做一個檢查。如果有buttons[index](索引不大於或小於所有按鈕陣列的長度),請使用index=0。然後,撥動buttons[index]並增量index

然後,您可以撥打setTimeout - 第一個參數是函數的名稱,第二個參數是在啓動之前要等待的時間量。

一旦超出此功能,請以相同的方式致電setTimeout

例子:http://jsfiddle.net/bVNx2/

+0

您的示例鏈接將逐個禁用按鈕,我想模擬點擊。 – Ossi 2011-05-27 03:55:24

+0

@Ossi哦,那你用'.toggle'表示了什麼?我以爲你的意思是禁用/啓用,因爲'toggle'不存在於元素上。隨着輕微的變化,你可以達到你想要的效果 - 打開你的控制檯,看到http://jsfiddle.net/bVNx2/1/ – Zirak 2011-05-27 11:06:16

+0

酷感謝,那個小提琴的東西很酷;) – Ossi 2011-05-27 11:26:14