[英]Why do my javascript integration in a django template does not work?
[英]What's the correct Javascript scope to work with my Django template?
我在Django中有一个带有foor循环的模板,看起来大致如下:
{% if items %}
<form method="post" name="managerform" id="managerform" action="">{% csrf_token %}
{{ managerform }}
</form>
{% for item in items %}
<script type='text/javascript'>
var yes = function yes() { manager(function(response) {
if(response && response.status == 'user') {
var object = '{{ item }}'
document.managerform.item.value = object;
document.managerform.preferences.value = "Yes";
document.managerform.submit();
}
else{
authUser(); } });}
</script>
...
<button onclick=yes()>Yes</button>
...
{% endfor %}
提交表单,问题是它总是提交最后的item
从items
。 我试着做yes
需要一个说法, aitem
,这并没有帮助,因为使用<button onclick=yes("{{item}}")>
未能完全和做:
<script>
aitem="{{ item }}"
</script>
<button onclick=yes(aitem)>
只是使用的最后一个item
,从items
试。
对任何人都有明显的解决方案吗?
将按钮的HTML更改为:
<button onclick='yes("{{item}}");'>Text</button>
并在你的django条件和循环之外完全取出<script>
代码,以便它始终可用,但将其更改为:
var yes = function (item) {
manager(function (response) {
if (response && response.status == 'user') {
var object = item;
document.managerform.item.value = object; // You could combine this and the previous line
document.managerform.preferences.value = "Yes";
document.managerform.submit();
} else {
authUser();
}
});
}
这样,你的django for
循环中唯一的东西就是按钮,每个结果都有一个不同的参数用于yes
函数。 yes
函数现在接受一个参数并按照您的意愿使用它。 您可能必须修改它以满足您的需求,因为您的代码片段似乎是一个示例,并不完全是您所拥有的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.