首页 > 解决方案 > 如何检查 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
);

标签: javascript

解决方案


使用脚本上的async 属性,当页面继续解析时,该脚本将在可用时立即异步运行。

它需要在为document.getElementById()加载页面后等待并运行

尝试更新如下:

document.addEventListener("DOMContentLoaded", function() {
  // your js code on here
  var Btn1Element = document.getElementById("1");
  ...
});

或者您可以删除脚本标签上的异步属性。

编辑:

检查{% if var %}您的上下文是否为真。

我认为这与 javascript 无关。html 标签(元素)不是由烧瓶视图引擎通过 if 条件创建的。

住在这里,您可以检查与您的不同之处


推荐阅读