我的 HTML 正文中有此内容:
<script src="{% static "jquery/sessionExists.js" %}"></script>
{% if context.alreadyOnSession == 'YES' %}
<h5 class="loginerror" onload="advSessionExists()">This session is already logged in</h5>
{% endif %}
这些{}
是 Django 代码。
sessionExists.js:
function advSessionExists(){
console.log('Just checking if its triggered');
}
我还尝试将原始 JavaScript 代码放入 HTML 正文中 <script type=text/javascript></script>
,我也尝试过 onbeforeprint
而不是onload
但它仍然没有显示我的 JS 方法。
The <h5> is being showed
,但没有触发我的 JS 方法。
最佳答案
The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div (or h5) is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.
当您 <h5>
时调用该函数元素已加载,只需在 <h5>
之后调用该函数即可django 中的元素 if statement
像这样:
{% if context.alreadyOnSession == 'YES' %}
<h5 class="loginerror">This session is already logged in</h5>
<script type="text/javascript">
advSessionExists();
</script>
{% endif %}
关于javascript - 为什么我的 javascript 方法没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54606275/