简体   繁体   English

为什么我的 javascript 方法没有被调用?

[英]Why is my javascript method not being called?

I have this in my HTML body:我的 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 %}

These {} are django code.这些{}是 Django 代码。

sessionExists.js: sessionExists.js:

function advSessionExists(){
    console.log('Just checking if its triggered');
}

Also I tried by putting my JavaScript code raw in the HTML body with <script type=text/javascript></script> , and also I tried with onbeforeprint instead of onload but it is still not showing my JS method.此外,我尝试将我的 JavaScript 代码放在带有<script type=text/javascript></script>的 HTML 正文中,并且我尝试使用onbeforeprint而不是onload但它仍然没有显示我的 JS 方法。

The <h5> is being showed , but not triggering my JS method. The <h5> is being showed ,但没有触发我的 JS 方法。

The onload event can only be used on the document(body) itself, frames, images, and scripts. onload 事件只能用于文档(正文)本身、框架、图像和脚本。 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. div(或 h5)不是外部资源,它作为主体的一部分加载,因此 onload 事件不适用于那里。

Via - How to add onload event to a div element?通过 - 如何将 onload 事件添加到 div 元素?


To invoke the function when your <h5> element has loaded, just call the function right after the <h5> element within your django if statement like this:要在<h5>元素加载后调用该函数,只需在 django if statement<h5>元素之后调用该函数,如下所示:

{% if context.alreadyOnSession == 'YES' %}

    <h5 class="loginerror">This session is already logged in</h5>

    <script type="text/javascript">
      advSessionExists();
    </script>

{% endif %}

尝试将onload="advSessionExists()添加到script标记。或者在您的脚本window.addEventListener('onload', advSessionExists);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM