Home > database >  Each data only appears 1 data, and when access each data the result is undefined
Each data only appears 1 data, and when access each data the result is undefined

Time:12-08

I have a product div which contains the data-product attribute, its value is object. And I want to put the product data into gtag.

but why when I do each, there is only 1 data? and when I want to access data.id and data.name why is it undefined?

$(document).ready(function(){
  const promotions = []
  
    $(".product-item").each(function(){
    const data = $(this).data('product');
    
    promotions.push({
      "id": data.id,
      "name": data.name
    })
  })
  
  //gtag('event', 'view_promotion', {
    //promotions
  //});
  
  $('.product-item').each(function(){
    $(this).on("click", function(e){
      const data = $('.product-item').data('product')
      console.log(data)
    })
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-item" data-product='{"id" : 123, "name" : "Product 1"}'>
  Product 1
</div>
<div class="product-item" data-product='{"id" : 124, "name" : "Product 2"}'>
  Product 2
</div>
<div class="product-item" data-product='{"id" : 125, "name" : "Product 3"}'>
  Product 3
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Change your HTML code, works for me:

<div class="product-item" data-product='{"id":124,"name":"Product 1"}'>
    Product 1
</div>
<div class="product-item" data-product='{"id":125,"name":"Product 2"}'>
    Product 2
</div>
<div class="product-item" data-product='{"id":126,"name":"Product 3"}'>
    Product 3
</div>

CodePudding user response:

As per the API the attribute value must be a valid JSON including quoted property names.

In your case it is not properly formatted as JSON hence, it is not working. Format your data-product as valid JSON.

Once the JSON is fixed, to loop over promotions

$(document).ready(function(){
  let promotions = []
  $(".product-item").each(function(){
    const data = $(this).data('product');
        
    promotions.push({
      "id": data.id,
      "name": data.name
    })
  })
      
           
  gtag('event', 'view_promotion', {
    promotions
  });
})
  • Related