简体   繁体   English

如何检查 JavaScript/Flask 中是否存在多个元素

[英]how to check if multiple elements exist in JavaScript/Flask

I have a js file with button click event listeners.我有一个带有按钮单击事件侦听器的 js 文件。 The problem is those buttons do not exist until flask sends the data over.问题是这些按钮在烧瓶发送数据之前不存在。 I want to only run the listeners if the elements exists or when the elements exist.如果元素存在或元素存在,我只想运行侦听器。

I am trying to solve this error that occurs:我正在尝试解决发生的此错误:

Uncaught TypeError: Cannot read property 'addEventListener' of null

HTML file: 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 file: 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
);

With async attribute on script, a script that will be run asynchronously as soon as it is available while the page continues the parsing.使用脚本上的async 属性当页面继续解析时,脚本将在可用异步运行

It needs to wait and run after page loaded for document.getElementById()document.getElementById()加载页面后需要等待并运行

Try to update as like:尝试更新如下:

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

or you could remove async attribute on script tag.或者您可以删除脚本标记上的异步属性。

EDITED:编辑:

check whether {% if var %} is true on your context.检查{% if var %}在您的上下文中是否为真。

i think it is not about javascript.我认为这与 javascript 无关。 html tags(elements) do not created by flask view engine by if condition. html 标签(元素)不是由 Flask 视图引擎通过 if 条件创建的。

live on here and you could check what is different from yours 住在这里,你可以检查什么与你的不同

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

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