简体   繁体   中英

How to pass parameter with a href and onclick function?

It is a very simple Javascript functionality but I am not able to get it worked. When I am trying to pass a parameter to an onclick method as follows:

<td><b><div id=linkInstall><a href="#" target=_self onClick="show(' + reports + ')" class=right>ABC</a></div></b></td>

the show() function treats "report" as a string instead of a variable. Here reports is a variable contains some value. Then I tried to escape the string as follows

<td><b><div id=linkInstall><a href="#" target=_self onClick="show(\'' + reports + \'')" class=right>ABC</a></div></b></td>

then it throws the following error:

Uncaught SyntaxError: Invalid or unexpected token

So what is going wrong in this case? How should I pass the variable instead of the string?

Thanks.

Since you said that you use Django and HTML, I think the error is with the templating syntax. Try passing the variable inside curly braces.

Example:

<td>
  <b>
    <div id=linkInstall>
      <a href="#" target=_self onClick="show({{ reports }})" class=right>ABC</a>
    </div>
  </b>
</td>

Please note that you need to pass the variable to the template as an argument using TemplateResponse

from django.template.response import TemplateResponse

def page_name(request, template_name="myapp/inculdes.html"):
    args = {}
    text = {"data":"data"}
    args['reports'] = text
    return TemplateResponse(request, template_name, args)

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