【问题标题】:How to listen to a html button through the backend javascript file?如何通过后端javascript文件监听一个html按钮?
【发布时间】:2023-02-04 17:07:55
【问题描述】:

我正在编写一个带有后端的网站,我想添加一个事件侦听器来侦听 ./public/index.html 中的按钮,但我不能执行 getElementById,因为当我执行“node app.js”时它说该文档不存在,因为 html 文件没有运行?

我尝试在 html 中使用“onclick”函数更新一个变量,当服务器发现该变量为真时,它会生成一个事件。注意:我使用 node.js

【问题讨论】:

    标签: javascript html node.js backend


    【解决方案1】:

    检查所有文件(HTML Style.css 和 script.js)是否可以找到彼此/是否在同一个文件夹中 - 如果是这样,如果您启动 HTML,则以下内容应该可以工作:

    HTML:

    !DOCTYPE html>
    <html lang="en" >
    <head>
      <meta charset="UTF-8">
      <title>Title you want</title>
      <link rel="stylesheet" href="./style.css">
    
    </head>
    <body>
    <!-- partial:index.partial.html -->
    <div id="tsparticles"></div>
    
    <button id="first-button">first button</button>
    
    <!-- partial -->
    </script><script  src="./script.js"></script>
    
    </body>
    </html>
    

    名为“style.css”的 CSS:

    body {
      margin: 0;
      font:normal 75% Arial, Helvetica, sans-serif;
    }
    
    canvas {
      display: block;
      vertical-align: bottom;
    }
    
    
    #first-button {
      position: absolute;
      top: 10px;
      right: 10px;
    }
    

    最后,名为“script.js”的 javascript 使用:

    const firstButton = document.getElementById("first-button");
    firstButton.addEventListener("click", function() {
    
    // add your code for what happens upon the button press here
    
    });
    
    

    我希望这会有所帮助 - 如果没有,请提供更多详细信息并包括您正在使用的代码。

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 2014-10-16
      相关资源
      最近更新 更多