Passing a function into an EJS template for use in an onclick event?

∥☆過路亽.° 提交于 2019-12-08 07:18:57

问题


I'm trying to pass a function into an EJS template and have it be set to an onclick event in the template. Is this possible?

In other words, something like this

var clickHandler = function() { console.log("I am in the click handler!"); }
var template = new EJS({ url: "/template.ejs"  });
var html = template.render({ clickHandler: clickHandler })
$("#target").html(html);

Where the template looks something like

<p onclick='clickHandler'>Click Me</p>

回答1:


  • You should put your js function in the .ejs file instead of the server file.
  • You should pass the function name instead of the entire function code.

app.js

var html = template.render({ clickHandler:"func1();" })

EJS

<p onclick='<%= clickHandler %>'>Click Me</p>

<script>
  function func1(){
    console.log("I am in the click handler 1!"); 
  }
  function func2(){
    console.log("I am in the click handler 2!"); 
  }
</script>


来源:https://stackoverflow.com/questions/38595247/passing-a-function-into-an-ejs-template-for-use-in-an-onclick-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!