How to pass value to a onclick function in (Jade)pug?

青春壹個敷衍的年華 提交于 2019-11-30 23:08:17

When adding attributes to an html element, you are already within the scope of pug, so you can just use pug variables like regular js variables.

button(type='button' class=' c-btn-blue c-btn-circle c-btn-uppercase' value="Read More" onclick='gotoBlog(' + val.link + ')')

I just used the code below and it worked for me (with pre and pos quotes)

button(type='button', onclick='someFunction("'+ yourObject.id +'")' ) PressMe

Use differing nested quotation marks so that you pass a string to your gotoBlog function. Here, I use single ticks within double ticks.

button(type='button' class=' c-btn-blue c-btn-circle c-btn-uppercase' value="Read More" onclick="gotoBlog( '#{val.link}' )")

In other words:

button( onclick= "myFunction('#{stringVariable}')" )

You just need to put onclick="myfunction(#{varible.atributo})"

Here a example:

table
thead
    tr
        th #ID
        th Description
        th Actions
tbody
    each item, i in itemlist
        tr
            th(scope='row') #{item.id}
            td #{item.description}
            td
                button(onclick="editItem(#{item.id})", title="Edit")
                    |  Edit

I came across a similar issues and solved it rather differently (by escaping params). In my case, I needed to pass the following template values to a javascript function as argument when a button is clicked

{
  url:"http://google.com",
  token: "Bearer your-token", 
  accountId: "abc123"
}

So the pug in my case looked as follow

button(onclick='authenticate(\'' + url + '\',\'' + token + '\',\'' + accountId + '\')') Login

And the resulting html is as follow

<button onclick="authenticate('http://google.com','Bearer your-token','abc123')">Login</button>

When using multiple parameters in a function, this did the trick:

'myFunction(' + '"' + varA + '"' + ',' + '"' + varB + '"' + ')'

NOTE: outer/inner/all quote marks can be ' (single) or " (double) quote marks, I used single and double quote marks for readability.

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