简体   繁体   English

如何使用href和onclick function传递参数?

[英]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.这是一个非常简单的 Javascript 功能,但我无法让它工作。 When I am trying to pass a parameter to an onclick method as follows:当我尝试将参数传递给 onclick 方法时,如下所示:

<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. show() function 将“报告”视为字符串而不是变量。 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.既然您说您使用 Django 和 HTML,我认为错误在于模板语法。 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请注意,您需要使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM