-2

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

我调用了全局数组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>
4

1 回答 1

1

那是因为您正在循环超出数组中的最后一项。

改变这个:

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

到:

for (var i = 0, count = tasks.length; i < count; i++) {
于 2012-10-18T22:53:47.690 回答