将点击事件绑定到输入元素

时间:2018-11-09 11:09:14

标签: javascript html node.js express

我试图在不使用模板引擎的情况下从服务器提供html文件。请找到以下用于启动服务器的脚本。

// script.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();

app.use(express.static(__dirname));

app.get("/", (req, res) => {
   res.set("Content-Type", "text/html");
   const f = require("./templates")();
   console.log(f);
   res.send(f);
});

app.listen(3103, () => console.log("hi"));

// template.js
const fs = require("fs");
const html = fs.readFileSync(__dirname + "/temp.html", "utf8");

module.exports = (variables) => {
   return html;
};

以下是我的html文件:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./script.js"></script> <!-- The click function was served in a different file -->
</head>
<body>
    <p>Home Page</p>

    <input type="button" value="Click Me" id="btn" onclick="click()">
    <script>

        console.log("hi");
        function click(){ console.log("_Button clicked"); }                
        //document.getElementById("btn").addEventListener("click", () => {
            //console.log("Button Clicked");
        //});

    </script>
</body>
</html>

我尝试了以下操作,但未成功:

  • 我在按钮元素中包含了click()内联,并且该函数在同一html文件的script标记中声明。这不起作用。

  • 我在script.js文件中包含了fromScript函数,并将该文件作为静态内容提供。这没有按预期工作。

然后,我使用addEventListener将click事件绑定到输入元素。现在,每当我单击按钮时,“按钮单击”消息都会打印两次。

将dom事件绑定到元素的正确/最佳做法是什么?

修改

感谢您的回答 Thijs Kramer 。但是问题出在函数名。

如果我将该功能命名为点击,则该功能无效。但是,如果我将其重命名为 fromScript ,则可以正常工作。

我们不应该使用“ click”作为函数名吗?

3 个答案:

答案 0 :(得分:1)

您的问题与快递无关:) 绑定点击事件的最佳实践例如如下:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <p>Home Page</p>

    <input type="button" value="Click Me" id="btn">
    <script>
        const button = document.getElementById("btn");
        button.addEventListener("click", () => {
            console.log("Button Clicked");
        });
    </script>
</body>
</html>

编辑:我想我知道你的意思:

如果将函数fromScript重命名为click,显然也必须更改onclick属性的值:

<input type="button" onclick="click()" />

答案 1 :(得分:0)

下面的代码应该可以正常工作:

// script.js
const express = require("express");
// const bodyParser = require("body-parser"); 
const app = express();

app.use(express.static(__dirname));
app.listen(3103, () => console.log("hi"));

然后node script.js,然后尝试通过访问http://localhost:3103/temp.html来访问它 ?

答案 2 :(得分:0)

您的命名问题的原因是HTMLElement API(所有html元素都继承自该API)具有click属性。它是function,用于通过程序触发元素上的点击事件。

  

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

为避免造成混乱和不可预测的行为,请始终确保对原型链中继承和内置的属性命名明确。