简体   繁体   English

用django作为JS的字符串传递不起作用

[英]Pass as string for JS with django not working

The table I have so far, when rendered, properly displays the job numbers which are formatted individually as: '15-215' or '15-552' 到目前为止,我拥有的表格在呈现时正确显示了分别格式化为“ 15-215”或“ 15-552”的作业编号

I want to pass each job number on the table so that when I click each TD it passes the job number into my javascript. 我想传递表格上的每个作业编号,以便当我单击每个TD时,它将作业编号传递到我的JavaScript中。 It took me a while to diagnose that I need to pass as string otherwise it will evaluate 15-215 and then pass that. 我花了一段时间才诊断出我需要以字符串形式传递,否则它将评估为15-215,然后将其传递。

My html document is like below: 我的html文档如下所示:

    {% for a in obj %}
    ...

 <tr data-toggle="collapse" data-target="#demo{{forloop.counter}}" class="accordion-toggle">

        <td onclick="test(\'' + {{a.jobnum}} + '\')">{{a.jobnum}}</td>
    ...
    {% endfor %}

My js is like: 我的js就像:

function test(y) {
  alert(y);
  document.getElementById("123").innerHTML = y;
  }

I then have: 然后我有:

<p id="123">1</p>

But when I click the relevant td I get neither an alert nor the <p> updating 但是,当我单击相关的td时,既没有警报也没有得到<p>更新

I would do this a little bit different: 我会做些不同:

template 模板

{% for a in obj %}
    ...

<tr data-toggle="collapse" data-target="#demo{{forloop.counter}}" class="accordion-toggle">

   <td data-jobnum='{{ a.jobnum }}' class="test">{{a.jobnum}}</td>
    ...
{% endfor %}

js(jquery) js(jQuery的)

$('.test').click(function(){
    var value = $(this).data('jobnum');
    alert(value);
})

Now you can do any javascript with the value . 现在,您可以使用value执行任何JavaScript。

Note 注意

I used Jquery but you can do this with js also. 我使用了Jquery,但是您也可以使用js来做到这一点。

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

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