gpt4 book ai didi

javascript - 如何编写双重嵌套 for 循环的计数代码?

转载 作者:行者123 更新时间:2023-11-28 01:32:58 25 4
gpt4 key购买 nike

我试图将件号传递到我的 html 中。这将用于通过 JavaScript 更新所选标签的内容。我的所有标签都是由 django 中的双重嵌套 for 循环创建的。但从我的尝试来看,我没有成功。

这是 JavaScript 代码:

$('td#'+new_data['piece_number']).html(new_data['img']);

这是有问题的双重嵌套 for 循环:

<table id="table" bgcolor="{{puzzle.color_hash}}">
<tbody>
{% for x in n_rows %}
<tr id='r{{x}}'>
{% for y in n_cols %}
<td id='{{count}}' height='{{puzzle.piece_res_height}}' width='{{puzzle.piece_res_width}}'>
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>

我想要 {{count}} 中的总迭代计数,但根据我的理解,django 不允许您在渲染器中进行变量操作

我正在寻找结果,例如逐列表格...

1 2 3

4 5 6

7 8 9

其中有 3 行和 3 列。 9 件。每个都有一个 td id 的件号

即第 2 行第 2 列的 td id 为 5

最佳答案

您可以将两个变量而不是一个 count 发送到 html 文件并更改 id 命名的 ida。

<td id='r{{x}}d{{y}}' height='{{puzzle.piece_res_height}}' width='{{puzzle.piece_res_width}}'>

编辑 - 正确的解决方案

好的,我有两个解决方案给你。

两者都使用 custom template filters .

文件app/templatetags/default_filters.py

from django import template
register = template.Library()

#first way
def mod(value, arg):
return value % arg == 0

#second way
@register.filter(name='multiply')
def multiply(value, arg):
return value*arg

register.filter('mod', mod)

上下文发送到模板

class MainSiteView(TemplateView):
template_name = "main_page.html"

def get_context_data(self, **kwargs):
context = super(MainSiteView, self).get_context_data(**kwargs)
n_rows = n_cols = 2
context['max_nums'] = n_rows * n_cols
context['n_rows'] = [0, 1]
context['n_cols'] = [0, 1]
context['number_of_columns'] = 2
context['range'] = [x for x in range(n_cols * n_rows)]
return context

和模板

{% load default_filters %}
<table id="_table" bgcolor="{{puzzle.color_hash}}">
<tbody>
{% for x in range %}
{% if not forloop.counter|mod:number_of_columns %}
<tr id='_r{{x}}'>
{% endif %}
<td id='_{{forloop.counter0}}' height='{{puzzle.piece_res_height}}' width='{{puzzle.piece_res_width}}'>
({{forloop.counter0}})
</td>
{% if forloop.counter|mod:number_of_columns %}
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
<table id="table" bgcolor="{{puzzle.color_hash}}">
<tbody>
{% for x in n_rows %}
<tr id='r{{x}}'>
{% for y in n_cols %}
<td id='{{x|multiply:number_of_columns|add:y}}' height='{{puzzle.piece_res_height}}' width='{{puzzle.piece_res_width}}'>
[{{x|multiply:number_of_columns|add:y}}]
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>

关于javascript - 如何编写双重嵌套 for 循环的计数代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895254/

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