简体   繁体   中英

In Jade, how to pass parameters in the onclick function call

a(id='myLinkTag' onclick='myFunction(' + user._id + ')' href='') Delete

Here user._id is the variable and trying to pass that value to myFunction .

syntaxError: Invalid or unexpected token

The problem here is that javascript is expecting quotes around functions. What jade is making is <a id='myLinkTag' onclick='myFunction(userid) href=''>

This is not what javascript is expecting, Javascript expects a valid variable name to be given to its onclick functions. There are two choices:

  • If you are SURE that there is NO WAY for user._id to ever be anything other than a string ONLY CONTAINING alphanumeric characters ( new RegExp(/^(A-Za-z0-9)+$/) ) then put quotes in myFunction: a(id='myLinkTag' onclick='myFunction(\\'' + user._id + '\\')' href='') Delete

  • If user._id can be more than alphanumeric characters, you can instead use jade to set a class and a custom attribute like a(id='myLinkTag' class="myclass" userid=user._id href='') Delete then in javascript you can:

:

 $(".myclass").click(function(e){ var userid = $(e.target).attr("userid"); console.log(userid); alert(userid); }); 
 Jade would be: a(id='myLinkTag' class="myclass" userid=user._id href='#') a(id='myLinkTag2' class="myclass" userid=user2._id href='#') a(id='myLinkTag3' class="myclass" userid=user3._id href='#') 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="myclass" userid="myuserid" href="#">link</a> <a class="myclass" userid="myuserid2" href="#">link2</a> <a class="myclass" userid="myuserid3" href="#">link3</a> 

使用不同的嵌套引号,以便您将字符串传递给函数。

a(id='myLinkTag' onclick="myFunction(' + user._id + ')" href='') Delete

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