将函数传递给EJS模板以用于onclick事件? [英] Passing a function into an EJS template for use in an onclick event?

查看:994
本文介绍了将函数传递给EJS模板以用于onclick事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将函数传递给EJS模板,并将其设置为模板中的onclick事件。这可能吗?

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?

换句话说,就像这样

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);

模板看起来像

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


推荐答案


  • 你应该把你的 js 函数在 .ejs 文件而不是服务器文件中。

  • 你应该传递函数名而不是整个函数代码。

    • 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>
      

      这篇关于将函数传递给EJS模板以用于onclick事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆