为什么我的javascript for循环输出什么都没有

时间:2012-10-18 22:40:09

标签: javascript

当我使用下面的代码时,它不向屏幕输出任何内容。

我有一个名为tasks[]的全局数组,这是我试图运行的函数:

function addTask() {
'use strict';

var task = document.getElementById('task');
var outputTask = document.getElementById('taskOutput');
var outputList = document.getElementById('outputList');

var taskMessage = '';

if (task.value) {
    tasks[tasks.length] = task;
    taskMessage = 'You have ' + tasks.length + ' task(s) in your to-do list.';

    if(output.textContent !== undefined) {
        outputTask.textContent = taskMessage;   
    } else {
        outputTask.innerText = taskMessage;
    }


    for (var i = 0, count = tasks.length; i <= count; i++) {
        var listItem = document.createElement('h3');
        var textNode = document.createTextNode(tasks[i]);
        listItem.appendChild(textNode);
        outputList.appendChild(listItem);
    }

}// End task.value IF.
return false;
}// end addTask() function

这是javascript正在访问的HTML。当我在任务输入字段中输入一个值并按下提交时,我希望输出到outputList div中的屏幕为H3。

    <form id="theForm" name="theForm" />
<fieldset>
<legend>Enter the starting and ending dates of the task</legend>
<label for="start">Start</label>
<input type="text" name="start" id="start" placeholder="MM/DD/YYYY or Today" required />

<label for="end">End</label>
<input type="text" name="end" id="end" placeholder="MM/DD/YYYY" required />
</fieldset>
<fieldset><legend>Enter a Task For This Time Period</legend>
<div>
<label for="task">Task</label>
<input type="text" name="task" id="task" required />
</div>
</fieldset>
<input type="submit" value="Add It!" id="submit" />
</form>
</div>

<div id="output"></div>
<div id="taskOutput"></div>
<div id="outputList"></div>

1 个答案:

答案 0 :(得分:1)

那是因为你循环超出了数组中的最后一项。

改变这个:

for (var i = 0, count = tasks.length; i <= count; i++) {

为:

for (var i = 0, count = tasks.length; i < count; i++) {