2017-12-20 1 views
0

자바 스크립트를 사용하여 페이지를 스크랩하여 Google 데이터 레이어 배열을 채우려고합니다. 아래 코드는 콘솔 확인시 HTML에 나열된 모든 항목을 성공적으로 통과합니다. 아래 예제 코드 에서처럼 세 가지 항목을 모두 밀어 넣을 올바른 dataLayer.push 함수를 작성하는 데 어려움을 겪고 있습니다.JS를 사용하여 페이지를 긁어 내고 변수를 GTM 데이터 레이어로 푸시하는 방법

누군가 도와 주실 수 있습니까?

참고 : 'ID'와 '수익'을 무시해도됩니다.

$("#theList li").each(function() { 
 
    
 
    var $this=$(this); 
 
    scrapeProductName=$this.find('.name').text(); 
 
    scrapeProductPrice=$this.find('.price').text(); 
 
    scrapeProductQuantity=$this.find('.quantity').text(); 
 
    
 
    console.log('product: ' + scrapeProductName + '; price: ' + scrapeProductPrice + '; quantity: ' + scrapeProductQuantity); 
 
    
 
}); 
 

 
dataLayer = []; 
 

 
dataLayer.push({ 
 
    'ecommerce': { 
 
    'purchase': { 
 
     'actionField': { 
 
     'id': '11111111', 'revenue': '999.99' 
 
     }, 
 
     'products': [ 
 
     
 
     // start product list 
 
     
 
     { 
 
     'name': scrapeProductName, 
 
     'price': scrapeProductPrice, 
 
     'quantity': scrapeProductQuantity 
 
     } 
 
     
 
     // end product list 
 
     
 
     ] 
 
    } 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<ul id="theList"> 
 
    <li> 
 
    <div class="name">banana</div> 
 
    <div class="price">1.00</div> 
 
    <div class="quantity">3</div> 
 
    </li> 
 
    <li> 
 
    <div class="name">apple</div> 
 
    <div class="price">2.00</div> 
 
    <div class="quantity">5</div> 
 
    </li> 
 
    <li> 
 
    <div class="name">pear</div> 
 
    <div class="price">3.50</div> 
 
    <div class="quantity">1</div> 
 
    </li> 
 
</ul>

+0

것 같다 당신의 'each' 함수 내에서'dataLayer.push'를 호출합니다. 또한 각 'li'내의 항목에는 문제를 일으킬 수도 있고 발생시키지 않을 수도있는 상충되는 ID가 있지만 이는 모범 사례가 아닙니다. – James

+0

안녕하세요 @ 제임스, 당신은 ID에 대한 올바른, 그 클래스가 있어야합니다. 실제 페이지는 여기에서 사용하기에 적합하지 않은보다 복잡한 구조를 가지고 있기 때문에이 예제에서는 HTML을 빠르게 작성했습니다. 나는 지금 오류를 바로 잡을 것이다. – Klikerko

답변

2

다음, 각 기능에 별도로 제품의 배열을 빌드 dataLayer.push 호출에서 단일 엔티티로 첨부 : 당신이해야처럼

var products = []; 

$("#theList li").each(function() { 

    var $this=$(this); 
    scrapeProductName=$this.find('.name').text(); 
    scrapeProductPrice=$this.find('.price').text(); 
    scrapeProductQuantity=$this.find('.quantity').text(); 

    console.log('product: ' + scrapeProductName + '; price: ' + scrapeProductPrice + '; quantity: ' + scrapeProductQuantity); 

    products.push({name: scrapeProductName, price: scrapeProductPrice, quantity: scrapeProductQuantity}); 

}); 

dataLayer = []; 

dataLayer.push({ 
    'ecommerce': { 
    'purchase': { 
     'actionField': { 
     'id': '11111111', 'revenue': '999.99' 
     }, 
     'products': products 
    } 
    } 
}); 
관련 문제