如何将值传递给(Jade)pug中的onclick函数

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

本文关键字:pug 中的 onclick 函数 Jade 值传      更新时间:2023-09-26

我刚接触翡翠,被这个问题困住了。我想我已经尝试了StackOverflow帖子中的所有内容,但仍然一无所获。

我尝试过的事情

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

1:8 Uncaught SyntaxError: Invalid or unexpected token

改为!{val.link}

误差

Uncaught SyntaxError: Unexpected token .

将其更改为"!{val.link}""#{val.link}"只是给我字符串可以理解。顺便说一句,value .link是一个字符串

给出value .link表示Uncaught ReferenceError: val is not defined

我现在别无选择。

谢谢

当你给html元素添加属性时,你已经在pug的作用域中了,所以你可以像使用常规js变量一样使用pug变量。

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

我刚刚使用了前置前置引号的代码,它工作了:

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

你只需要输入onclick="myfunction(#{variable . attributo})"

这里有一个例子:

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

使用不同的嵌套引号,以便将字符串传递给gotoBlog函数。这里,我使用了双引号中的单引号。

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

换句话说:

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

太晚了,我知道

但是,这可能是有用的!

`${}`

所以代码是

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

太晚了,但上面的大多数选项都不适合我,但这个

button(onclick='gotoBlog('+'"'+val.link+'"'+')')

或简单的:

onclick=`gotoBlog('${val.link}')`

将value .link转换为字符串。

我遇到了一个类似的问题,并以不同的方式解决了它(通过转义参数)。在我的例子中,我需要在单击按钮时将以下template values作为参数传递给javascript函数

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

在我的例子中,pug的格式如下

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

生成的html如下

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

当在函数中使用多个参数时,可以这样做:

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

注意:外部/内部/所有引号可以是'(单)或"(双)引号,我使用单引号和双引号是为了可读性。

button(type='button', onClick='function(' " + someValue + ''')') Text

在onClick函数中使用我传递给pug的值