2011-04-20 79 views
0

我有一個數組。從數組中選擇值

var array = [0,1,2,4]; 
var index; 

現在我有四個按鈕。我可以隨機點擊任意按鈕,我需要將索引值更新爲第一個按鈕的值爲0,第二個按鈕的值爲1,第四個按鈕的值爲2,第三個按鈕的值爲3。

+2

偉大的故事!謝謝。 – 2011-04-20 15:29:41

+0

大聲笑..這個問題聽起來很奇怪 – theJava 2011-04-20 15:32:10

+0

我沒有看到一個問題,這就是爲什麼我正在咆哮..但其他人似乎已經弄清楚,所以你去了。 – 2011-04-20 15:33:00

回答

1

HTML:

<input type="button" onclick="javascript:SetIndex(this)" value="one" /> 
<input type="button" onclick="javascript:SetIndex(this)" value="two" /> 
<input type="button" onclick="javascript:SetIndex(this)" value="three" /> 
<input type="button" onclick="javascript:SetIndex(this)" value="four" /> 

的JavaScript:

var array = [0,1,2,4]; 
var index = 0; 

function SetIndex(obj) 
{ 
    // check if index is out of range and it might be useful 
    // to see if this button already has an index assigned 
    if (index < array.length && isNaN(obj.index)) 
    { 
     obj.title = array[index]; // hover to see index... 
     obj.index = array[index]; 
     index++; 
    } 
} 

工作示例:http://jsfiddle.net/hunter/eS4qy/

+0

不錯。現在,我們該怎麼辦?順便說一句,你可以從paste:P中刪除'javascript:'部分 – KooiInc 2011-04-20 16:56:52

1

難道這是你想要什麼:

<button onclick="index=0">1</button> 
<button onclick="index=1">2</button> 
<button onclick="index=2">3</button> 
<button onclick="index=3">4</button> 

+0

可疑,但你永遠不知道 – hunter 2011-04-20 15:33:09

1
<input type="button" onclick="javascript:setIndex(0)" value="one" /> 
<input type="button" onclick="javascript:setIndex(1)" value="two" /> 
<input type="button" onclick="javascript:setIndex(2)" value="three" /> 
<input type="button" onclick="javascript:setIndex(3)" value="four" /> 

<script type="text/javascript"> 
    var index = 0; 

    function setIndex(i) { 
     index = i; 
    } 
</script>