Grey Ooi Grey Ooi - 6 months ago 8
jQuery Question

Remove duplicated value that generated by element data

I have a group of images, each of the image have

data-type="type,type"
, so in order to make my life easier I intend to grab the data-type, and make them into an array (wrapped each of them in span) and append them to an "category" element.

$('li.grid-item').each(function () {
// grab a reference to the current li
var $el = $(this);
// get the url from its data-class attribute
var arr = $el.find('img').data('type').split(',');

$.each(arr, function (index, value) {
$el.find('.category').append('<span>' + value + '</span>');
$el.addClass(value);
});
});


<li class="grid-item">
<figure>
<img src="img/sticker/still/sticker_30.png" alt="sticker" title="You know I'm good" data-type="others/" data-price="9 bahts" data-alt="img/sticker/ani/sticker_30.gif" />
</figure>
<a href="#">
<span class="download ala_carte">CONTINUE</span>
</a>
<div class="category"></div>
</li>


It work fine but duplicated 20 of each value, please help. How to remove those duplicated array value? Please help, thanks in advance.

Answer

I think it's better to collect all existing types first in on array (and only add new values to it, if there weren't already existing). Afterwards, you could add span elements for each type. And you should only have one "category" container to list all types.

Update

Your function is executed to often (more than 20 times), because you are calling it everytime your $grid.imagesLoaded() makes progress. Call it when you are "done". Try replacing

$grid.imagesLoaded().progress()

with

$grid.imagesLoaded().done()

to call your function only once after all images are loaded. Additionally you could empty the category container before re-filling it.