简体   繁体   English

Pug / Jade:onClick调用函数并传递参数

[英]Pug / Jade : onClick call function and pass param

Demo code here : https://codepen.io/iShawnWang/pen/ZvBGRv 此处的演示代码: https : //codepen.io/iShawnWang/pen/ZvBGRv

All i want is to call a js function and pass a param, 我想要的只是调用js函数并传递参数,
I have tried the following answer, but not works 我已经尝试了以下答案,但是没有用

And as discussed in the Pug Github issues below, 正如下面的Pug Github问题中所讨论的,

Event handlers like onclick can only be added through HTML or client-side JavaScript. This is not something Jade can help you with.

So what is the best practice to add onclick listener on Pug template ? 那么在Pug模板上添加onclick侦听器的最佳实践是什么?

I solved it by myself : https://github.com/pugjs/pug/issues/2933 我自己解决了: https : //github.com/pugjs/pug/issues/2933

a.postTitle(onclick=`viewPost(${JSON.stringify(file)})`)= file.name

then, I can receive an object at viewPost function, take care of the ` symbol 然后,我可以在viewPost函数中收到一个对象, 注意`符号

So what is the best practice to add onclick listener on Pug template ? 那么在Pug模板上添加onclick侦听器的最佳实践是什么?

From my own experiences, I recommend adding script tag with the event handler logic to the template, and declaring the onclick without any backticks, grave-accents, string-interpolation marks: 根据我自己的经验,我建议将带有事件处理程序逻辑的script标签添加到模板中,并声明onclick而不带有任何反引号,重音符号,字符串插值标记:

`

String interpolation marks will fail with some UglifyJs build steps (usually common in Prod configurations): 字符串插值标记将因某些UglifyJs构建步骤而失败(通常在Prod配置中很常见):

this-will-${fail}-in-some-UglifyJs-versions

An example of what I mean would look like this: 我的意思的示例如下所示:

// my template.pug

script
  function myFunction(varA, varB){
    // do something...
  }

- var someVar = "this is a string, but the value could come from anywhere, really"

div(onclick='myFunction(' + '"' + someVar + '"' + ',' + '"' + someVar + '"' + ')')

The linked question now covers this in an answer . 链接的问题现在在答案中涵盖了这一点

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

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