I have 6 list items
$('.favorite-tag-group li').each(function(){
console.log("hi");
});
This code however is displaying “hi” 24 times in console.
The only thing I can think of that might be causing it to bug out is because my list items arent all in the same list.
For example, .favorite-tag-group is a div that always contains a ul. In some cases, that ul will only have 1 li. Sometimes it may have 2.
Here’s a sample of what that might look like
div.favorite-tag-group
ul
li
li
li
div.favorite-tag-group
ul
li
div.favorite-tag-group
ul
li
div.favorite-tag-group
ul
li
li
All I’m trying to do is run through .each() li so that I can remove duplicates ;/
Some real html:
<div class="favorite-tag-group">
<h4>gobty</h4>
<ul class="resources led-view">
<li class="clearfix r-tutorial" data-id="22">
</li>
</ul>
</div>
<div class="favorite-tag-group">
<h4>javascript</h4>
<ul class="resources led-view">
<li class="clearfix r-tutorial" data-id="24">
</li>
</ul>
</div>
<div class="favorite-tag-group">
<h4>macvim</h4>
<ul class="resources led-view">
<li class="clearfix r-tool" data-id="21">
</li>
</ul>
</div>
here is the real function. When i paste the .each() directly into console it works, but inside this function it doesnt work:
// collapse tags functionality
$('.collapse-tags').click(function(e){
e.preventDefault();
$('.favorites-helpers, .favorite-tag-group h4').slideUp(200, function(){
var seen = {};
$('.favorite-tag-group li').each(function(){
//console.log("hi");
var currentId = $(this).data('id');
if (seen[currentId]) {
$(this).slideUp(200);
} else {
seen[currentId] = true;
}
});
});
});
As in my comment above… With a bit of further explanation.
It’s because
$('.favorites-helpers, .favorite-tag-group h4')will be causing multiple elements toslideUp(), and therefore the callback gets executed multiple times. Movingvar seen = {}to inside the callback resets the variable as an empty object in each callback. You’ll still iterate over your list items more than once (as seen by multipleconsole.log()s), but you’ll slide the same duplicateli‘s up each time this way.You asked: “The one thing im still confused about is, why would it not be able to see the scope of seen if it were outside the callback? wouldnt variable scope say that it could see it because its outside the function?”
Yes, you are right – the callback could see
seen, butseenwas never emptied/reset, and therefore after the second iteration of your callback, all of yourli‘s would have had.slideUp()called on them.Consider this: because it either slides the duplicate up, or adds the
idtoseen, on the second callback,.each()runs again, but it’s already full of all of your list itemsids.Hope this is clear enough, if not just comment below and I’ll try and come up with some examples.