简体   繁体   中英

Selecting values from Array

I have an array.

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

Now i have four buttons. I may click on any button at random order, i need the index value to be updated as 0 for the first button clicked, 1 for the second button, 2 for the fourth button and 3 for the third button.

is this is what you want:

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

?

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++;
    }
}

working example: http://jsfiddle.net/hunter/eS4qy/

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM