我有这个代码:
{% for review in reviews %}
<div>
{{ review.content }}
by {{ review.username }}
- timeDifference("{{ review.date_submitted }}")
</div>
{% endfor %}
第五行是一个js函数timeDifference,它将以文本形式返回时差,我想在其中插入js函数,该怎么做?
答案 0 :(得分:0)
无法执行这样的Js函数。并且在加载期间可能执行javascript函数并进行DOM操作。
HTML
<-- In for loop -->
<div onload="timeDifference( {{ review.id }}, {{ review.date_submitted }} );">
<p id="timeDifferenceElement{{ review.id }}"></p>
</div>
用Java语言
function timeDifference(id, date_submitted) {
const timeDifferenceElement = document.getElementById("timeDifferenceElement" + id)
// Do calculation
---
timeDifferenceElement.innerHTML = "something from the calculation"
}
答案 1 :(得分:0)
这是对我有用的解决方案,灵感来自Raja Simons的回答和How to add onload event to a div element?:
<div id="review{{review.id}}">
{{ review.content }} by {{ review.username }}
-
<p id="timeDifferenceElement{{ review.id }}"></p>
<script type="text/javascript">
timeDifferenceForDate( '{{ review.id }}', '{{ review.date_posted }}' );
</script>