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

标签 javascript python html django

我的 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.

Via - How to add onload event to a div element?


当您 <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/

相关文章:

javascript - 无法读取未定义的属性 'createManager'

javascript - Jasmine 中使用外部库进行单元测试

python - 如何在 xlsxwriter add_series() 中从行列表示法转换为 A1 表示法

html - Bootstrap 3 网格元素

java - 在 Android-Java 中操作 html 响应

javascript - jQuery Promise 不会触发 .then() 或 .done()

javascript - 从 youtube.com 上的 YouTube 播放器状态触发事件

python - 将python中生成的图像存储到Django数据库(MySQL)

python - 权限错误 : [Errno 13] in Python

javascript - 如何在输入字段中搜索特定单词