Using jQuery to get data attribute values with .each()

后端 未结 3 1344
甜味超标
甜味超标 2021-01-04 01:03

I have the following HTML with data attributes - I want to write some jQuery that will loop through the HTML and collect the data attributes and put them into an array - cou

相关标签:
3条回答
  • 2021-01-04 01:30

    Use item.dataset.fullname instead.

    var multi = $('.winners');
    var winners_array = [];
    
    $.each(multi, function (index, item) {
        winners_array.push( {name: 'fullname', value: item.dataset.fullname} );  
    });
    
    console.log(winners_array);
    
    0 讨论(0)
  • 2021-01-04 01:47

    item is not a jQuery object, the arguments for each are the index and the native DOM element

    var multi = $('.winners');
    var winners_array = [];
    
    $.each(multi, function (index, item) {
        winners_array.push( {name: 'fullname', value: $(item).data('fullname')} );  
    });
    

    using a map would be easier

    var winners_array = $.map($('.winners'), function(el) {
         return {name: 'fullname', value: $(el).data('fullname')}
    });
    
    0 讨论(0)
  • 2021-01-04 01:47

    I understand you should use $(item), instead data only. Kindly find the code below:

    <script type="text/javascript">
            var multi = $('.winners');
            var winners_array = [];
    
            $.each(multi, function (index, item) {
                winners_array.push( {name: 'fullname', value: $(item).data('fullname')} );  
            });
    
            console.log(winners_array);
        </script>
    
    0 讨论(0)
提交回复
热议问题