Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

Django template tag / jquery for- iteration?

Just a small problem i can't get my head around right now:

I have a list of objects presented in a table. One of the objects values is a score. I can use a Django template tag to show this as a number but i want to use my jquery plug-in to show stars instead. Not sure how to iterate over this. I'm trying this:

{% 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 %}

And further down i got this:

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

The problem is that it shows the same score for every object with the jquery..

EDIT: I got it to work with this:

<script>
$('.raty').each(function() {
  $(this).raty({ readOnly: true, score: $(this).attr('data-number') });
});
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A div element does not have a value attribute. Try using a hidden input element. Something like this:

<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>

And then in your script:

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

So, for each of elements having a class of hidden_score, you will get their value make a "raty" with the elemens belonging to the parent of each element (so they are siblings) with the correct score.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...