문제

I have a jQuery object which I get via code such as this:

var elements = $('#all_cats_holder div.wSelect-option-selected').detach();

The code it gets will be something such as:

<div class="wSelect-option wSelect-option-selected"><div class="wSelect-option-value" data-val="2">Some stupid cat #2</div></div>
<div class="wSelect-option wSelect-option-selected"><div class="wSelect-option-value" data-val="3">Some stupid cat #3</div></div>
<div class="wSelect-option wSelect-option-selected"><div class="wSelect-option-value" data-val="4">Some stupid cat #4</div></div>

Now I'm trying to loop through this data and get the value of data-val but I can't seem to get it to work.

My code:

var mr_val;

$.each(elements, function(index, el) {

    mr_val = el.data('val');

    alert(mr_val);            

});

I don't even get an alert at all.

도움이 되었습니까?

해결책

Why not just make it an array with $.map

var mr_val = $.map(elements, function(el) {
    return $(el).find('[data-val]').data('val');
});

FIDDLE

or with each

var mr_val;

$.each(elements, function(index, el) {

    mr_val = $(el).find('div').data('val');

    alert(mr_val);            

});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top