How I can do a foreach
or similar in jQuery? I need that when the user clicks in the <span>
, add the class inactive
to all <div>
s with the vote active
class in the <ul>
.
I've tried with the .each
method, but it doesn't work.
I have this HTML:
<ul class="suggestions inactive">
<li id="s2">
<div class="id">2</div>
<div class="vote inactive">
<span class="up"></span>
<span class="down"></span>
</div>
<div class="text">test2</div>
<div class="rating">2</div>
</li>
<li id="s3">
<div class="id">3</div>
<div class="vote active">
<span class="up"></span>
<span class="down"></span>
</div>
<div class="text">test3</div>
<div class="rating">0</div>
</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="script.js"></script>
And this script:
$(document).ready(function(){
var ul = $('ul.suggestions');
// Listening of a click on a UP or DOWN arrow:
$('div.vote span').live('click',function(){
var elem = $(this),
parent = elem.parent(),
li = elem.closest('li'),
ratingDiv = li.find('.rating'),
id = li.attr('id').replace('s',''),
v = 1,
ul2 = elem.closest('li').parent();
// If the user's already voted:
if(parent.hasClass('inactive')){
return false;
}
if(ul2.hasClass('inactive')){
return false;
}
//If the user's already voted, add following class
parent.removeClass('active').addClass('inactive');
ul2.removeClass('active').addClass('inactive');
if(elem.hasClass('down')){
v = -1;
}
// Incrementing the counter on the right:
ratingDiv.text(v + +ratingDiv.text());
// Turning all the LI elements into an array
// and sorting it on the number of votes:
var arr = $.makeArray(ul.find('li')).sort(function(l,r){
return +$('.rating',r).text() - +$('.rating',l).text();
});
// Adding the sorted LIs to the UL
ul.html(arr);
// Sending an AJAX request
$.get('ajax.php',{action:'vote',vote:v,'id':id});
});