问题
I am new to jade and stuck on this issue. I think I have tried everything from the StackOverflow posts and still at nothing.
The things I have tried
button(type='button' class=' c-btn-blue c-btn-circle c-btn-uppercase' value="Read More" onclick='gotoBlog( #{val.link} )')
Error
1:8 Uncaught SyntaxError: Invalid or unexpected token
Changing it to !{val.link}
Error
Uncaught SyntaxError: Unexpected token .
Changing it to "!{val.link}"
and "#{val.link}"
just gives me string understandably so. BTW val.link is a string
Just giving val.link says Uncaught ReferenceError: val is not defined
I am out of options now. Help will be appreciated.
Thanks
回答1:
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 + ')')
回答2:
I just used the code below and it worked for me (with pre and pos quotes)
button(type='button', onclick='someFunction("'+ yourObject.id +'")' ) PressMe
回答3:
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}')" )
回答4:
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
回答5:
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>
回答6:
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.
回答7:
button(type='button', onClick='function(\'' + someValue + '\')') Text
This worked for me to use values that I passed to pug inside an onClick function.
来源:https://stackoverflow.com/questions/39160264/how-to-pass-value-to-a-onclick-function-in-jadepug