Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django模板变量从{%for%}循环转换为Javascript_Javascript_Django_Django Templates - Fatal编程技术网

Django模板变量从{%for%}循环转换为Javascript

Django模板变量从{%for%}循环转换为Javascript,javascript,django,django-templates,Javascript,Django,Django Templates,这是一个Django模板,它遍历记录。每个记录都包含一个JS函数填充的div。为了让JS知道该做什么,它需要从每个for循环迭代中获取一个变量并使用它。我不知道如何实现这一目标,也不知道这是否可能。也许需要一种不同的方法,在一个单独的JS对象实例中记录触发计时器,我不知道 ----------html----------------------- {% for match in upcoming_matches %} ... <tr> <td> Match title

这是一个Django模板,它遍历记录。每个记录都包含一个JS函数填充的div。为了让JS知道该做什么,它需要从每个for循环迭代中获取一个变量并使用它。我不知道如何实现这一目标,也不知道这是否可能。也许需要一种不同的方法,在一个单独的JS对象实例中记录触发计时器,我不知道

----------html-----------------------

{% for match in upcoming_matches %}
...

<tr>
<td> Match title </td>
<td> Match time </td>
<td> Starts in: </td>
<tr>

<tr>
<td> {{ match.title }} </td>
<td> {{ match.start_time }} </td>
<td> <div id="matchCountdown"/></td>
<tr>

...

{% endfor %}
$(function () {

        var start_date = {{ match.start_date }}; // Obviously I can't access vars from for loop, I could access upcoming_matches but not the ones from for loop


        var matchDate = new Date(start_date.getTime() 

     $('#matchCountdown').countdown({until: matchDate});

    });

您还可以在代码的javascript部分中使用{%for%}循环。如果在html模板中编写此项:

<script type="text/javascript">
    $(function() {
        {% for match in upcoming_matches %}
            var match_date_{{ match.id }} = new Date({{ match.start_date }}).getTime();
            $('#matchCountdown_{{ match.id }}').countdown({until: match_date_{{ match.id }});
        {% endfor %}
    });
</script>

$(函数(){
{即将到来的_matches%}
var match_date{{{match.id}}=新日期({{match.start_date}).getTime();
$('matchCountdown'{{match.id}')。倒计时({until:match_date{{match.id}});
{%endfor%}
});

此外,在本例中,
变为

您可以将开始日期作为matchCountdown的属性输出。然后在JavaScript中选择它,处理它并使用Countdown插件输出

模板代码:

JavaScript:

$('.matchCountdown').each(function() {
    this = $(this);
    var start_date = this.attr('start');
    var matchDate = new Date(start_date).getTime();
    this.countdown({until: matchDate});
});
此方法只需要模板代码中的一个循环和Javscript中的一个循环来查找和启用项。另外,需要注意的是,“matchCountdown”应该是一个类,而不是div的id,因为它不是唯一的。

请查看jQuery的

使用它,您可以像这样在DOM中存储数据

<div id="myDiv" data-somedata="myimportantdata"></div>

你能试着把你想要完成的事情说得更具体一点吗?+1你的解决方案比我发布的答案要优雅得多。
$("#myDiv").data("somedata");