javascript - 从数组中选择值

标签 javascript

我有一个数组。

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

现在我有四个按钮。我可以按随机顺序单击任何按钮,我需要将索引值更新为 0(代表单击的第一个按钮)、1(代表第二个按钮)、2(代表第四个按钮)、3(代表第三个按钮)。

最佳答案

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/

关于javascript - 从数组中选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732804/

相关文章:

javascript - 如何使用 d3 获取 svg 图像的缩放级别

javascript - AngularJS - 使用命名空间解析 JSON feed

javascript - 使用回调更新 Ionic UI 元素

javascript - 我如何在电子商务表格上要求最低数量?

javascript - 将类添加到 ckeditor 中选定的图像

javascript - 检查 JQuery 1.11.1 上是否已经存在点击事件

javascript - 防止Reducer属性嵌套在状态中

javascript - Material UI 和 React : ThemeManager is not a constructor

javascript - HTML5 Canvas toDataURL 在 for 循环中始终相同

javascript - SurroundContents() 进行更改 `live` ?