简体   繁体   中英

Pug / Jade : onClick call function and pass param

Demo code here : https://codepen.io/iShawnWang/pen/ZvBGRv

All i want is to call a js function and pass a param,
I have tried the following answer, but not works

And as discussed in the Pug Github issues below,

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 ?

I solved it by myself : 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

So what is the best practice to add onclick listener on Pug template ?

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:

`

String interpolation marks will fail with some UglifyJs build steps (usually common in Prod configurations):

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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