【发布时间】:2017-01-04 02:58:38
【问题描述】:
我试图了解为什么选项卡没有使用通过表单输入的值进行更新。
程序由三部分组成:
- tasks10.html 带有表单和 tasks10.js 调用
- utilities10.js 将函数分组到对象 U = {...} 以创建命名空间。用于填充选项卡的函数名为 plusTask。
- tasks10.js 是一个立即调用的函数,其目的是将“onsubmit”事件分配给函数 U.plusTask
我把声明 var tasks = [];在 tasks10.js => 失败;在 plusTask => 失败。在这两种情况下,选项卡都没有填充,索引仍然保持为 0。
HTML
<!doctype html>
<head>
<title>List</title>
<link rel="stylesheet" href="css/form.css">
</head>
<body>
<form action="#" method="post" id="theForm">
<fieldset><legend>Enter an Item To Be Done</legend>
<div><label for="task">Task</label><input type="text" name="task" id="task" required></div>
<input type="submit" value="Add It!" id="submit">
<div id="output"></div>
<p id='test'> -- </p>
</fieldset>
</form>
<script src="js/utilities10.js"></script>
<script src="js/tasks10.js"></script>
</body>
</html>
tasks10.js
(function() { // immediately invoked function
'use strict';
//window.addEventListener('onsubmit',U.plusTask,false);
U.$('theForm').onsubmit = U.plusTask;
})(); // End of anonymous function.
utilities10.js
var U = {
// For getting the document element by ID:
$: function(id) {
'use strict';
if (typeof id == 'string') {
//alert("cxcwcw $"+ id);
return document.getElementById(id);
}
}, // End of $() function.
plusTask : function() {
var tasks = [];
// Function called when the form is submitted.
// Function adds a task to the global array.
function innerCalculate(){
alert(tasks.length);
'use strict';
// Get the task:
//var task =this.$('task');
var task =U.$('task'); alert("task : " + task);
//var task =document.getElementById('task');
// Reference to where the output goes:
//var output = this.$('output');
var output = U.$('output');
//var output = document.getElementById('output');
alert("in");
// For the output:
var message = '';
if (task.value) {
U.$('test').innerHTML = tasks.length;
//document.getElementById('test').innerHTML = tasks.length;
// Add the item to the array:
tasks.push(task.value);
// Update the page:
message = '<h2>To-Do</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
message += '<li>' + this.tasks[i] + ' - ' + count + '</li>';
}
message += '</ol>';
output.innerHTML = message;
} // End of task.value IF.
// Return false to prevent subssmission:
return false;
} // End of innerCalculate
innerCalculate();
} // End of plusTask function
} // End of U
【问题讨论】:
标签: javascript namespaces global