【问题标题】:Django template tag / jquery for- iteration?Django模板标签/ jquery for-迭代?
【发布时间】:2014-03-12 22:56:25
【问题描述】:

只是一个小问题,我现在想不通:

我有一个表格中显示的对象列表。对象值之一是分数。我可以使用 Django 模板标签将其显示为数字,但我想使用我的 jquery 插件来显示星星。不知道如何迭代这个。我正在尝试这个:

{% for result in mylist %}

<td>{{ result.type }}</td>
<td>{{ result.description }}</td>
<td>{{ result.rating.votes }}</td>

<td><div class="raty" data-number="{{ result.rating.score }}"></div></td>

{% endfor %}

然后我得到了这个:

<script>
$('.raty').raty({ readOnly: true, score: $('.raty').attr('value') });
</script>

问题是它显示每个对象与 jquery 相同的分数..

编辑:我得到了它的工作:

<script>
$('.raty').each(function() {
  $(this).raty({ readOnly: true, score: $(this).attr('data-number') });
});
</script>

【问题讨论】:

    标签: jquery django templates raty


    【解决方案1】:

    div 元素没有value 属性。尝试使用隐藏的输入元素。像这样的:

    <table>
        {% for result in mylist %}
            <tr><td><input type='hidden' class='hidden_score' value='{{ result.rating.score }}'></input><div class="raty"></div></td></tr>
         {% endfor %}
    </table>
    

    然后在你的脚本中:

    $.each($('.hidden_score'), function( index, value ) {
        var myval = $(this).val();
        $(this).parent().find( '.raty').raty({ readOnly:true, score:myval});
    });
    

    因此,对于每个具有 hidden_​​score 类的元素,您将获得它们的值,与属于每个元素的父元素(因此它们是兄弟姐妹)的元素组成一个“比例”,并具有正确的分数。

    【讨论】:

    • 感谢您的回答。不,这不正是我所想的。现在我得到了每个分数的输入字段,只有第一个显示了一些星星(不是正确的分数,只是“空星”)。但我会尝试修改它,看看我得到了什么。
    • 没有错。第一个字段显示星星+输入字段,其余对象显示带有数字的输入字段..
    • 哎呀我忘了在输入中添加 type='hidden' !
    • 是的,这会更有意义:) 但问题是迭代它只显示第一个对象的值,如星星。
    • 糟糕!我还没有看到 {% for %}...请检查我的更新答案!
    猜你喜欢
    • 2016-09-02
    • 2022-07-17
    • 2011-04-30
    • 1970-01-01
    • 2012-07-13
    • 2017-02-16
    • 2011-04-06
    • 2011-08-16
    相关资源
    最近更新 更多