使用Javascript中的onclick转到数组的下一个索引

时间:2014-01-18 23:38:11

标签: javascript arrays object onclick

如果我含糊不清或者我的代码难以理解,我会事先道歉,我还在学习这些东西。我正在尝试显示存储在数组中的信息。我想在单击按钮时显示此信息,再次单击该按钮时,数组中的下一个索引将显示其信息。

我需要帮助设置一个前进到数组下一个索引的函数。谢谢!

(函数(){

var students =[                       //array of information
    {name:'john', 
    address:{
        address:'821 Imaginary St',
        city:'Chicago',
        state:'Il'},
    gpa:[4.0,3.5,3.8]},

    {name:'jim',
    address:{
        address:'127 fake Rd',
        city:'Orlando',
        state:'Fl'},
        gpa:[2.5,3.3,3.6]}];

    var redBut = document.querySelector('.buttonred');
redBut.onclick = getInfo;
var count = 0;

    function getInfo(){

      var stn = students[0];
      if(count<3){
         count++;

        document.getElementById('name').innerHTML = 'Name: ' + stn.name;          //this is what is to be displayed when the button is clicked
        document.getElementById('address').innerHTML = 'Address: ' + stn.address.address + " " + stn.address.city + ", " + stn.address.state;
        document.getElementById('gpa').innerHTML = 'GPA: ' + stn.gpa[0] +", " + stn.gpa[1] + ", " + stn.gpa[2];
        document.getElementById('date').innerHTML = 'Date: ' + d.toLocaleDateString();
        document.getElementById('gpaavg').innerHTML = 'Average GPA: ' + gpas;

}

}

1 个答案:

答案 0 :(得分:0)

我想你想要:var stn = students[count];

而不是:var stn = students[0];

(DOH!)