gpt4 book ai didi

javascript - django 模板中的 javascript : error display with javascript funciton

转载 作者:行者123 更新时间:2023-11-30 11:50:34 25 4
gpt4 key购买 nike

更新:

所以现在我将代码更改为:

<script>
function myFunction(calid) {
document.getElementById(calid).innerHTML = "<ul><li>" + calid + "</li>" + "</ul>";
}
</script>

{% for calibrations in equipment.calibration_set.all %}


<ul>
<li>
<p onclick="myFunction( {{calibrations.id}} ) "> {{calibrations.cal_date}} </p>
<div id = {{calibrations.id}}> YES </div>


</li>
</ul>

{% endfor %}

而且效果很好。谢谢!

但是还有一个更奇怪的问题:当我试图向函数添加更多参数以便它可以显示更多信息时,它只是停止工作,这真的很奇怪,因为我唯一改变的是添加一个新参数。所以如果我试试这个:

<script>
function myFunction(calid, calby) {
document.getElementById(calid).innerHTML = "<ul><li>" + calid + "</li>" + "<li>" + calby + "</li>" + "</ul>";
}
</script>

{% for calibrations in equipment.calibration_set.all %}


<ul>
<li>
<p onclick="myFunction( {{calibrations.id}}, {{calibrations.cal_by}} ) "> {{calibrations.cal_date}} </p>
<div id = {{calibrations.id}}> YES </div>


</li>
</ul>

{% endfor %}

然后当我点击日期时,没有任何反应。

  1. 这怎么错了?
  2. 也许我应该使用 JSON 将模型数据传递到 javascript?

Old post: I will just dump my code here first:

{% for calibrations in equipment.calibration_set.all %}
<script>
function myFunction(cal_id) {
document.getElementById(cal_id).innerHTML = "<ul><li>{{calibrations.id}}</li></ul>";
}
</script>
<ul>
<li>
<p onclick="myFunction( {{calibrations.id}} )">{{calibrations.cal_date}}</p>
<div id = {{calibrations.id}}> YES </div>


</li>
</ul>

so calibration is a foreign key of equipment. And here I would like to display a list of calibration associated to a equipment, and using the date of calibration as a javascript onclick event so that a user can click to display the detail information of this calibration. The problem I have is that now even if there are multiple calibrations, clicking the calibration date will change the "Yes" under it to the id of latest calibration.

[![enter image description here][1]][1]

Like in the picture, I clicked the first and second calibration date and expect the text below it to be 1 and 2 respectively.

Could somebody point out what's wrong here?

[1]: http://i.stack.imgur.com/kRFkl.png

最佳答案

您在每个循环中创建具有相同名称的 javascript 函数。这就是为什么所有点击都返回相同结果的原因。

简单的解决方案是:

function myFunction(cal_id) {
document.getElementById(cal_id).innerHTML = "<ul><li>" + cal_id + "</li></ul>";
}

但一般来说,在每个循环中都创建新函数(尤其是同名函数)是不对的。

关于javascript - django 模板中的 javascript : error display with javascript funciton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39603958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com