简体   繁体   English

为什么我的 onclick 按钮在页面加载时调用 function?

[英]Why is my onclick button is calling a function when the page loads?

I'm working in NodeJS with Express.我正在使用 Express 在 NodeJS 中工作。 I'm having a problem with my EJS client side file right now for a button click.我的 EJS 客户端文件现在出现问题,无法单击按钮。

I have a function from a JS file imported to my EJS file, and I can call it by doing <% helper.test() %>我从导入到我的 EJS 文件的 JS 文件中有一个 function,我可以通过执行<% helper.test() %>来调用它

However, my button decides to call this function whenever the page loads instead of doing it when I click the button.但是,我的按钮决定在页面加载时调用此 function,而不是在单击按钮时调用。

<button onclick="<% helper.test() %>">Button Test</button>

If I change the button code to be如果我将按钮代码更改为

<button onclick="helper.test()">Button Test</button>

it says that helper isn't defined.它说没有定义助手。 I'm new to all this, any help would be greatly appreciated.我对这一切都很陌生,任何帮助将不胜感激。

it is probably for the parenthesis on the attribute "onclick".它可能是属性“onclick”的括号。 Try the code of your button this manner:以这种方式尝试按钮的代码:

<button onclick="<% helper.test %>">Button Test</button>

Since helper.test is a method defined on the server, the client is not able to call this method directly.由于helper.test是服务端定义的方法,客户端无法直接调用该方法。 The client and the server are separate applications that can only communicate with each other using HTTP.客户端和服务器是单独的应用程序,只能使用 HTTP 相互通信。

You can instead define an HTTP endpoint on your server that invokes helper.test and have your button make a request to that endpoint.您可以改为在您的服务器上定义一个 HTTP 端点,该端点调用helper.test并让您的按钮向该端点发出请求。

Here's a rough example:这是一个粗略的例子:

Server:服务器:

router.get("/helper_test", () => {
    helper.test();
});

Client:客户:

<button onclick="callHelperTest()">">Button Test</button>

<script>
function callHelperTest() {
    fetch("/helper_test");
}
</script>

Try this, remove () from helper.test()试试这个,从 helper.test() 中删除 ()

<button onclick="helper.test">Button Test</button>

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

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