使用 Django 模板,我正在尝试在 javascript 中添加倒计时。将脚本显式放入 HTML 中确实有效,但在加载时无效。我想我已经接近了,但我无法弄清楚缺少什么:/。
这是一段工作代码:
<!DOCTYPE html>
<head>
{% load staticfiles %}
</head>
<body>
{% if remaining_time %}
<script>
function startTimer(duration, display) {
var timer = duration;
var end = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(end);
document.form_submit_answer.submit()
}
}, 1000);
}
window.onload = function () {
var allowed_time_seconds = "{{remaining_time | safe}}",
display = document.querySelector('#time');
startTimer(allowed_time_seconds, display);
};
</script>
{% endif %}
{{ current_question.title }}
<div>
<form name="form_submit_answer" action="{% url 'assignment_completion' token current_question_num %}"
method="post">
{% csrf_token %}
{{ form }}
<div>
{% if next_question %}
<input type="submit" value="Send your answer and go to the next question">
{% else %}
<input type="submit" value="Send your answer and end the assignment">
{% endif %}
</div>
</form>
</div>
<div>
TOKEN : {{ token }}
</div>
{% if remaining_time %}
<div>Time remaining : <span id="time">{{initial_remaining_time}}</span></div>
{% endif %}
</body>
</html>
但是当我从 HTML 中删除脚本并将其放入/static/js/timer.js
然后导入时<head>
,它不再起作用,initial_remaining_time
显示但它不会每秒递减。
这是我的一段代码,它不起作用:
<head>
{% load staticfiles %}
{% if remaining_time %}
<script src="{ % static 'js/timer.js' % }"></script>
{% endif %}
</head>
预期结果:显示初始时间,然后递减到 0,在 0 时发送表格!
实际上,当将 timer.js 放入 /static/js/timer.js 时,只显示初始时间,然后什么都没有发生,就好像从未加载和播放过 javascript。
Traceback : (nkFjLIDrya1BrWd2bqYnq7TC5bpGCRGW3HcDXa6cqYI is a token)
[18/Jul/2019 11:12:32] "GET /nkFjLIDrya1BrWd2bqYnq7TC5bpGCRGW3HcDXa6cqYI/2 HTTP/1.1" 200 1017
Not Found: /nkFjLIDrya1BrWd2bqYnq7TC5bpGCRGW3HcDXa6cqYI/{ % static 'js/timer.js' % }
[18/Jul/2019 11:12:32] "GET /nkFjLIDrya1BrWd2bqYnq7TC5bpGCRGW3HcDXa6cqYI/%7B%20%%20static%20'js/timer.js'%20%%20%7D HTTP/1.1" 404 2617