从 get 请求调用 ejs 中 onClick 处理程序上的函数时出现问题。该功能必须位于服务器上,因为将执行对数据库等的操作。我是如何尝试的:
app.get('/opencase', ensureAuthenticated, function (req, res) {
const values = Object.values(caseData.caseDataJson);
const randomValue = values[parseInt(Math.random() * values.length)]
function openCase() {
switch (randomValue.name) {
case "100 gold":
console.log(randomValue.description)
break;
case "1000 gold":
console.log(randomValue.description)
break;
case "10000 gold":
console.log(randomValue.description)
break;
default:
console.log("Oh, shit.")
break;
}
};
res.render('opencase', {
user: req.user,
clickHandler: openCase(),
caseName: randomValue.name,
caseDescription: randomValue.description,
});
});
<button onclick="<%= clickHandler %>">Open</button>
但是该函数不是在点击时调用的,而是在页面加载时调用的。
这是函数调用:
这是函数作为处理程序的分配: