javascript - 如何检查 JavaScript/Flask 中是否存在多个元素
问题描述
我有一个带有按钮单击事件侦听器的 js 文件。问题是这些按钮在烧瓶发送数据之前不存在。我只想在元素存在或元素存在时运行侦听器。
我正在尝试解决发生的此错误:
Uncaught TypeError: Cannot read property 'addEventListener' of null
HTML 文件:
<html>
<body>
{% if var %}
<div>
<h1>Hello {{var}}</h1>
<button id="1">Click me</button>
<button id="2">Click me</button>
<button id="3">Click me</button>
<button id="4">Click me</button>
</div>
{% endif %}
<script async src="{{ url_for('static', filename='js/buttons.js') }}"></script>
</body>
<html>
JS文件:
var Btn1Element = document.getElementById("1");
var Btn2Element = document.getElementById("2");
var Btn3Element = document.getElementById("3");
var Btn4Element = document.getElementById("4");
Btn1Element.addEventListener(
"click",
() => {
window.location = "/1";
},
false
);
Btn2Element.addEventListener(
"click",
() => {
window.location = "/2";
},
false
);
Btn3Element.addEventListener(
"click",
() => {
window.location = "/3";
},
false
);
Btn4Element.addEventListener(
"click",
() => {
window.location = "/4";
},
false
);
解决方案
使用脚本上的async 属性,当页面继续解析时,该脚本将在可用时立即异步运行。
它需要在为document.getElementById()加载页面后等待并运行
尝试更新如下:
document.addEventListener("DOMContentLoaded", function() {
// your js code on here
var Btn1Element = document.getElementById("1");
...
});
或者您可以删除脚本标签上的异步属性。
编辑:
检查{% if var %}
您的上下文是否为真。
我认为这与 javascript 无关。html 标签(元素)不是由烧瓶视图引擎通过 if 条件创建的。
住在这里,您可以检查与您的不同之处
推荐阅读
- python - 对于带有 pytest-cov 的 pytest:如何为覆盖版本 >= 5 指定 parallel=True
- flutter - 如何使底部导航栏在我的应用程序的每个页面上都可见?
- mysql - 如何将排序的数据插入另一个 sql 数据表?
- php - 从 wpdb 填充下拉列表
- delphi - 确定 DUnitX 中的测试顺序?
- java - 如果选择了特定项目,如何从微调器中获取选择项目并更改图像?
- javascript - 如何在具有“严格”和“非严格”模式的常规箭头 fn 中确定正确的“this”?
- javascript - 当信息不正确时用户提交时如何将内容保留在表单中,这样他们就不必输入所有内容
- robotframework - 在 Robot Framework 中运行 Netconf 不会返回正确的输出
- python - 用python解码/编码十六进制数字