简体   繁体   English

如何通过模板参数数组将参数传递给js函数

[英]How to pass parameter to js function from template parameter array

I generated in tornado template table with cities and I am trying to have like last column details button 我在龙卷风模板表中生成了城市,并试图像上一列详细信息按钮一样

{% if globals().has_key('results')  %}
   {% for result in results %}
     <tr>
         <td>{{result['name']}}</td>
         <td>{{result['citizens']}}</td>
         <td style="width:100px; height:100px;">
          <div class="ui-grid-b">
          <a class="ui-block-a ui-icon-detail" onclick="showDetails('{{id}}',{{result['city_id']}});" data-role="ui-li-aside" data-icon="right_arrow" data-theme="a"></a>
          </div>
         </td>
     </tr>
    {% end %}
{% end %}

and on click to load on another page with parameters in url. 然后单击以加载另一个带有url参数的页面。

<script type="text/javascript">
    function showDetails(id, city_id)
       {
          window.location = '/cities?id='+id+'&city_id='+city_id;
        }
</script>

How to pass parameters to show details function ? 如何传递参数以显示详细信息功能? (I cannot use ', I tried with \\" but it doesn't work). Results is list of dictionaries with keys name, citizens, city_id. {{ }} is used by tornado template to access passed parameter. (我不能使用',我尝试用\\“,但是它不起作用。)结果是字典列表,其中包含键名称,公民,city_id。龙卷风模板使用{{}}访问传递的参数。

   showDetails = function (id, city_id)
       {
          window.location = '/cities?id='+id+'&city_id='+city_id;
        }

I think is the easy way 我认为这是简单的方法

The variable inside the braces will be output directly (or, the string representation of it), so it depends what it is set to. 大括号内的变量将直接输出(或字符串的字符串表示形式),因此取决于设置的内容。

eg if you have: 例如,如果您有:

id = 'foo'
results = [{ 'city_id': 'bar' }]

and you are passing them to the template, then this line: 然后将它们传递给模板,然后此行:

showDetails('{{id}}',{{result['city_id']}});

will be output as follows (you can confirm this with view source): 将输出如下(您可以通过查看源代码确认):

showDetails('foo',bar);

I'm guessing you're missing the quotes around {{result['city_id']}} , unless result['city_id'] is an integer, in which case it should work. 我猜想您会丢失{{result['city_id']}}周围的引号,除非result['city_id']是整数,在这种情况下应该可以使用。 Single or double quotes are both fine in JavaScript. 在JavaScript中,单引号或双引号都可以。

However, as @Pete already pointed out, "on click to load on another page with parameters in url" is what we have the href attribute for. 但是,正如@Pete已经指出的那样,“具有单击功能,可在带有url参数的另一个页面上单击”是我们的href属性。 You can save yourself a lot of work and potential brokenness with: 您可以使用以下方法节省许多工作和潜在的故障:

<a href="/cities?id={{ id }}&city_id={{ result['city_id'] }}" ....></a>

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

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