简体   繁体   English

调用外部 js function 作为 ejs onclick 事件

[英]Calling an external js function as ejs onclick event

I have a nodejs application that renders an ejs file called main.ejs including a button.我有一个 nodejs 应用程序,它呈现一个名为 main.ejs 的 ejs 文件,包括一个按钮。 I'd like to declare a function in an external javascript file that I can call it in the onclick event of that button(in main.ejs).我想在一个外部 javascript 文件中声明一个 function 文件,我可以在该按钮的 onclick 事件中调用它(在 main.ejs 中)。 But every time I run the app, by rendering the page, that function will be called automatically, but when I click on the button it won't be called!但是每次我运行应用程序时,通过渲染页面,function 会被自动调用,但是当我点击按钮时它不会被调用!

(I need to mention that I have already tried writing this function directly in main.ejs in a script tag, and it perfectly works. But I'm persisting in moving it to a respective js file) (我需要提一下,我已经尝试在脚本标记中直接在 main.ejs 中编写这个 function,它非常有效。但我坚持将其移动到相应的 js 文件中)

functions.js (the external js file) functions.js(外部 js 文件)

function optionClick() {
    console.log("Yoohooo!!");
}

module.exports = {
    optionClickFunc: optionClick
};

server.js服务器.js

var functions = require('./public/functions');

app.get('/question', (req, res) => {
 res.render('main.ejs', {
                data: {
                   function: functions.optionClickFunc
                }
            });
});

main.ejs主.ejs

<button id="submit-button" onclick="'<%= data.function() %>';"> START </button>

And whenever I have this url in my browser: http://localhost:3000/question, I see the log message("Yoohooo!!") printed in the console without clicking on the button!每当我在我的浏览器中有这个 url 时:http://localhost:3000/question,我在控制台中看到打印的日志消息(“Yoohooo !!”)而不点击按钮! While it doesn't print the message when I click the botton!!当我单击按钮时它不打印消息!

Any idea?任何想法? I really appreciate your time.我真的很感谢你的时间。

data.function is a function and when you call it in your server-side-code, you call it in your server side code. data.functionfunction ,当您在服务器端代码中调用它时,您在服务器端代码中调用它。

When you write HTML you need to write strings and the string representing the value of the onclick attribute needs to be JavaScript source code .编写 HTML 时需要编写字符串,表示onclick属性值的字符串需要是JavaScript 源代码 ( data.function , as mentioned, is a function not a string of source code.) The client will compile that source code and execute it. (如前所述, data.function是 function 不是源代码字符串。)客户端将编译该源代码并执行它。


Your server-side and client-side code might both be written in JavaScript, but they are two different programs running in two different environments (Node.js and the browser) which will usually (less so during development) run on two different computers.您的服务器端和客户端代码可能都用 JavaScript 编写,但它们是在两个不同环境(Node.js 和浏览器)中运行的两个不同程序,通常(在开发过程中较少)在两台不同的计算机上运行。

Related: What is the difference between client-side and server-side programming?相关: 客户端和服务器端编程有什么区别?

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

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