我正在使用一个使用Morris.js创建图表的HTML页面。我添加了日历小部件以允许用户选择开始和结束日期,以及用于更新数据的按钮。我意识到如果我自动将日期设置为“今天”会很方便,因此图表在首次加载时已经有数据。一切正常:日期设置为今天,查询返回有效的JSON,图表显示正确的数据。但是,<input>
字段未更新,我无法弄清楚原因。另外值得注意的是,按下“空”字段上的按钮后,日期被正确设置,DO随后出现在输入中。以下是相关代码:
<script> // inside head tag
function updateCharts() {
startDate = document.getElementById("startDate").value;
endDate = document.getElementById("endDate").value;
scale = document.getElementById("scale").value;
console.log("before " + startDate);
if (startDate == "") {
console.log("empty start");
var today = new Date;
startDate = today.getFullYear() + "-" +
(today.getMonth() + 1) + "-" + // getMonth in range [0,11]
5;//today.getDate();
document.getElementById("startDate").value = startDate;
console.log("input " + document.getElementById("startDate").value);
}
if (endDate == "") {
console.log("empty end");
endDate = startDate;
document.getElementById("endDate").value = endDate;
console.log("output " + document.getElementById("endDate").value);
}
console.log("after " + startDate + " " + endDate);
var charts = ['providers', 'variance', 'cities', 'convertions', 'unique_ids'];
var len = charts.length;
for (var i = 0; i < len; i++) {
var chartType = charts[i]
chart(chartType, startDate, endDate, scale);
}
}
</script>
以下是输入标签:
<div id="dates" class="row">
<p>From: <input type="text" id="startDate" />
To: <input type="text" id="endDate" />
<select id="scale">
<option value="0">Hour</option>
<option value="1">Day</option>
<option value="2">Month</option>
</select>
<button value="Show" onclick="updateCharts()">Show</button>
</p>
</div>
我的脚本在身体的末尾调用函数:
<script>
window.onload = updateCharts();
</script>
</body>
加载后控制台输出,然后按下按钮:
before
index.html (line 41)
empty start
index.html (line 43)
input 2015-11-5
index.html (line 49)
empty end
index.html (line 52)
output 2015-11-5
index.html (line 55)
after 2015-11-5 2015-11-5
因为你可以看到在条件符号后由Javascript设置和检索的值(正确?),但它没有在浏览器中显示。
答案 0 :(得分:3)
尝试用window.onload = updateCharts
代替window.onload = updateCharts();
请参阅GlobalEventHandlers.onload,What is the different between window.onload = init(); and window.onload = init;