单击javascript循环数组

时间:2014-03-31 08:39:56

标签: javascript arrays

我有一个问题,当循环我的数组循环时;只显示最终元素。为什么?

MY JS:

var dom = new Array();


/*-----------------RIDDLES--------------*/
dom[0] = "How many cats..";
dom[1] = "How many dogs..";
dom[2] = "How many birds..";

function guess()
{
    for (var i = 0 ; i < dom.length ; i++)
    {
        document.getElementById("riddle").getElementsByTagName('p')[0].innerText = dom[i];
    }

}

我的HTML:

  <div id="riddle">
        <p>  </p>
    </div>


    <button  onclick="guess()">Next</button>

为什么不循环所有数组元素?

4 个答案:

答案 0 :(得分:2)

您可以像这样实现它:

var dom = new Array();

/*-----------------RIDDLES--------------*/
dom[0] = "How many cats..";
dom[1] = "How many dogs..";
dom[2] = "How many birds..";

// Initial pointer
var i = 0;

var p = document.getElementById("riddle").getElementsByTagName('p')[0];

function guess() {
    if (i < dom.length) {
        p.innerText = dom[i];
        i = i + 1;
    }
    else {
        alert('All solved!')
    }
}

// Display tyhe first one
guess();

演示:http://jsfiddle.net/7wucF/1/

答案 1 :(得分:1)

<强> HTML:

<div id="riddle">
    <p>  </p>
</div>


<button id="nxt">Next</button>

<强>使用Javascript:

var dom = ["How many cats..","How many dogs..","How many birds.."];
var index = -1;
document.getElementById("nxt").onclick= function() {
    // Prevent getting past length of array
    if((index + 1) >= dom.length) { return; }
    index++;
    document.getElementById("riddle").getElementsByTagName('p')[0].innerText = dom[index];
};

Fiddle

答案 2 :(得分:1)

最好不要在循环内部访问DOM方法,每次循环迭代时都会写入。并且DOM操作在js中很昂贵。

  

var dom = [];

/*-----------------RIDDLES--------------*/ 
dom[0] = "How many cats.."; 
dom[1] = "How many dogs.."; 
dom[2] = "How many birds..";

function guess() {
    var arr = []; 

    for (var i = 0 ; i < dom.length ; i++)
    {
       arr.push(dom[i]);
    }

    document.getElementById("riddle").getElementsByTagName('p')[0].innerText
     

= arr.join(&#39;&#39;);
      }

答案 3 :(得分:0)

我已经测试了你的代码,似乎是onclick事件无法正常运行,只是尝试使用addEventListener,就像fiddle

一样

代码:

var dom = new Array();
var i = 0;
/*-----------------RIDDLES--------------*/
dom[0] = "How many cats..";
dom[1] = "How many dogs..";
dom[2] = "How many birds..";

document.getElementById("b1").addEventListener("click",function(){
    var e = document.getElementById("riddle").getElementsByTagName('p')[0];
    e.innerHTML = dom[i];
    if(i>1)
        i=0
    else
        i++;
},false);

HTML:

<div id="riddle">
    <p></p>
</div>
<button  id="b1">Next</button>